Skip to content

Commit 68a2371

Browse files
committed
add lib
1 parent 552b41d commit 68a2371

File tree

8 files changed

+452
-0
lines changed

8 files changed

+452
-0
lines changed

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,33 @@
11
API для работы с сервисом Яндекс.Локатор
22
========================================
3+
Определение местоположения по IP
4+
5+
```php
6+
// использовать встроенный автозагрузчик, либо через composer
7+
require 'autoload.php';
8+
9+
$api = new \Yandex\Locator\Api('your_token');
10+
$api->setIp('88.88.88.88');
11+
12+
try {
13+
$api->load();
14+
} catch (\Yandex\Locator\Exception\CurlError $ex) {
15+
// ошибка curl
16+
} catch (\Yandex\Locator\Exception\ServerError $ex) {
17+
// ошибка Яндекса
18+
} catch (\Yandex\Locator\Exception $ex) {
19+
// какая-то другая ошибка (запроса, например)
20+
}
21+
22+
$response = $api->getResponse();
23+
// как определено положение
24+
$response->getType();
25+
// широта
26+
$response->getLatitude();
27+
// долгота
28+
$response->getLongitude();
29+
30+
// сериализация/десереализация объекта
31+
var_dump(unserialize(serialize($response)));
32+
33+
```

autoload.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
/**
3+
* Generated by "Autoload generator"
4+
* @link http://github.com/dmkuznetsov/php-autoloader
5+
* @date 2013-11-06 23:05
6+
*/
7+
function __dm_autoload_locator( $name )
8+
{
9+
$map = array (
10+
'Yandex\\Locator\\Api' => 'source/Yandex/Locator/Api.php',
11+
'Yandex\\Locator\\Exception' => 'source/Yandex/Locator/Exception.php',
12+
'Yandex\\Locator\\Exception\\CurlError' => 'source/Yandex/Locator/Exception/CurlError.php',
13+
'Yandex\\Locator\\Exception\\ServerError' => 'source/Yandex/Locator/Exception/ServerError.php',
14+
'Yandex\\Locator\\Response' => 'source/Yandex/Locator/Response.php',
15+
'Yandex\\Locator\\Transport' => 'source/Yandex/Locator/Transport.php',
16+
);
17+
if ( isset( $map[ $name ] ) )
18+
{
19+
require $map[ $name ];
20+
}
21+
}
22+
spl_autoload_register( '__dm_autoload_locator' );

source/Yandex/Locator/Api.php

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
<?php
2+
namespace Yandex\Locator;
3+
4+
/**
5+
* Class Api
6+
* @package Yandex\Locator
7+
* @author Dmitry Kuznetsov <[email protected]>
8+
* @license The MIT License (MIT)
9+
* @see http://api.yandex.ru/locator/
10+
*/
11+
class Api
12+
{
13+
/**
14+
* @var string Версия используемого api
15+
*/
16+
protected $_version = '1.0';
17+
/**
18+
* @var array
19+
*/
20+
protected $_filters = array();
21+
/**
22+
* @var \Yandex\Locator\Response|null
23+
*/
24+
protected $_response;
25+
26+
/**
27+
* @see http://api.yandex.ru/maps/form.xml
28+
* @param string $token
29+
* @param null|string $version
30+
*/
31+
public function __construct($token, $version = null)
32+
{
33+
if (!empty($version)) {
34+
$this->_version = (string)$version;
35+
}
36+
$this->_transport = new \Yandex\Locator\Transport();
37+
$this->_filters['common'] = array(
38+
'version' => $this->_version,
39+
'api_key' => $token
40+
);
41+
$this->reset();
42+
}
43+
44+
/**
45+
* Сброс фильтров
46+
* @return self
47+
*/
48+
public function reset()
49+
{
50+
$this->_filters['gsm_cells'] = array();
51+
$this->_filters['wifi_networks'] = array();
52+
$this->_filters['ip'] = array();
53+
return $this;
54+
}
55+
56+
/**
57+
* @throws Exception
58+
* @return self
59+
*/
60+
public function load()
61+
{
62+
$apiUrl = 'http://api.lbs.yandex.net/geolocation';
63+
$data = $this->_transport->post($apiUrl, $this->_filters);
64+
if ($data['code'] == 200) {
65+
$tmp = json_decode($data['data'], true);
66+
if (!is_null($tmp)) {
67+
$this->_response = new \Yandex\Locator\Response($tmp);
68+
} else {
69+
$msg = sprintf('Bad response: %s', var_export($data, true));
70+
throw new \Yandex\Locator\Exception(trim($msg));
71+
}
72+
} else {
73+
$msg = strip_tags($data['data']);
74+
throw new \Yandex\Locator\Exception(trim($msg), $data['code']);
75+
}
76+
return $this;
77+
}
78+
79+
/**
80+
* @return null|Response
81+
*/
82+
public function getResponse()
83+
{
84+
return $this->_response;
85+
}
86+
87+
/**
88+
* Добавление описание соты
89+
* @param int $countryCode Код страны (MCC, Mobile Country Code)
90+
* @param int $operatorId Код сети мобильной связи (MNC, Mobile Network Code).
91+
* @param int $cellId Идентификатор соты (CID, Cell Identifier)
92+
* @param int $lac Код местоположения (LAC, Location area code).
93+
* @param null|int $signalStrength Уровень сигнала (dBm). Элемент зарезервирован
94+
* @param null|int $age Время в миллисекундах, прошедшее с момента получения данных. Элемент зарезервирован
95+
* @return self
96+
*/
97+
public function setGsmCells($countryCode, $operatorId, $cellId, $lac, $signalStrength = null, $age = null)
98+
{
99+
$data = array(
100+
'countrycode' => $countryCode,
101+
'operatorid' => $operatorId,
102+
'cellid' => $cellId,
103+
'lac' => $lac
104+
);
105+
if (!empty($signalStrength)) {
106+
$data['signal_strength'] = $signalStrength;
107+
}
108+
if (!empty($age)) {
109+
$data['age'] = $age;
110+
}
111+
$this->_filters['gsm_cells'][] = $data;
112+
return $this;
113+
}
114+
115+
/**
116+
* Описание wi-fi сети
117+
* @param string $mac MAC-адрес в символьном представлении. Байты могут разделяться дефисом, точкой, двоеточием или указываться слитно без разделителя
118+
* @param null|int $signalStrength Уровень сигнала (dBm). Элемент зарезервирован
119+
* @param null|int $age Время в миллисекундах, прошедшее с момента получения данных. Элемент зарезервирован
120+
* @return self
121+
*/
122+
public function setWiFiNetworks($mac, $signalStrength = null, $age = null)
123+
{
124+
$data = array(
125+
'mac' => (string)$mac
126+
);
127+
if (!empty($signalStrength)) {
128+
$data['signal_strength'] = $signalStrength;
129+
}
130+
if (!empty($age)) {
131+
$data['age'] = $age;
132+
}
133+
$this->_filters['wifi_networks'][] = $data;
134+
return $this;
135+
}
136+
137+
/**
138+
* Описание IP
139+
* @param string $ip IP-адрес мобильного устройства
140+
* @return self
141+
*/
142+
public function setIp($ip)
143+
{
144+
$this->_filters['ip']['address_v4'] = (string)$ip;
145+
return $this;
146+
}
147+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
namespace Yandex\Locator;
3+
4+
/**
5+
* Class Exception
6+
* @package Yandex\Locator
7+
* @author Dmitry Kuznetsov <[email protected]>
8+
* @license The MIT License (MIT)
9+
*/
10+
class Exception extends \Exception
11+
{
12+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
namespace Yandex\Locator\Exception;
3+
4+
/**
5+
* Class CurlError
6+
* @package Yandex\Locator\Exception
7+
* @author Dmitry Kuznetsov <[email protected]>
8+
* @license The MIT License (MIT)
9+
*/
10+
class CurlError extends \Yandex\Locator\Exception
11+
{
12+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
namespace Yandex\Locator\Exception;
3+
4+
/**
5+
* Class ServerError
6+
* @package Yandex\Locator\Exception
7+
* @author Dmitry Kuznetsov <[email protected]>
8+
* @license The MIT License (MIT)
9+
*/
10+
class ServerError extends \Yandex\Locator\Exception
11+
{
12+
}

source/Yandex/Locator/Response.php

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
<?php
2+
namespace Yandex\Locator;
3+
4+
/**
5+
* Class Response
6+
* @package Yandex\Locator
7+
* @author Dmitry Kuznetsov <[email protected]>
8+
* @license The MIT License (MIT)
9+
* @see http://api.yandex.ru/locator/doc/dg/api/geolocation-api_json.xml?lang=ru#id04EE5318
10+
*/
11+
class Response implements \Serializable
12+
{
13+
/**
14+
* @var float Широта в градусах. Имеет десятичное представление с точностью до семи знаков после запятой
15+
*/
16+
protected $_latitude;
17+
/**
18+
* @var float Долгота в градусах. Имеет десятичное представление с точностью до семи знаков после запятой
19+
*/
20+
protected $_longitude;
21+
/**
22+
* @var float Высота над поверхностью мирового океана
23+
*/
24+
protected $_altitude;
25+
/**
26+
* @var float Максимальное расстояние от указанной точки, в пределах которого находится мобильное устройство
27+
*/
28+
protected $_precision;
29+
/**
30+
* @var float Максимальное отклонение от указанной высоты
31+
*/
32+
protected $_altitudePrecision;
33+
/**
34+
* @var string Обозначение способа, которым определено местоположение
35+
*/
36+
protected $_type;
37+
38+
public function __construct(array $data)
39+
{
40+
if (is_array($data)) {
41+
$this->_latitude = isset($data['position']['latitude']) && !empty($data['position']['latitude']) ? (float)$data['position']['latitude'] : 0.0;
42+
$this->_longitude = isset($data['position']['longitude']) && !empty($data['position']['longitude']) ? (float)$data['position']['longitude'] : 0.0;
43+
$this->_altitude = isset($data['position']['altitude']) && !empty($data['position']['altitude']) ? (float)$data['position']['altitude'] : 0.0;
44+
$this->_precision = isset($data['position']['precision']) && !empty($data['position']['precision']) ? (float)$data['position']['precision'] : 0.0;
45+
$this->_altitudePrecision = isset($data['position']['altitude_precision']) && !empty($data['position']['altitude_precision']) ? (float)$data['position']['altitude_precision'] : 0.0;
46+
$this->_type = isset($data['position']['type']) && !empty($data['position']['type']) ? trim($data['position']['type']) : 0.0;
47+
}
48+
}
49+
50+
/**
51+
* (PHP 5 >= 5.1.0)<br/>
52+
* String representation of object
53+
* @link http://php.net/manual/en/serializable.serialize.php
54+
* @see \Serializable::serialize()
55+
* @return string the string representation of the object or null
56+
*/
57+
public function serialize()
58+
{
59+
$data = array();
60+
$reflection = new \ReflectionClass(get_called_class());
61+
foreach ($reflection->getProperties() as $property) {
62+
$property->setAccessible(true);
63+
$key = $property->getName();
64+
$value = $property->getValue($this);
65+
$data[$key] = $value;
66+
}
67+
return serialize($data);
68+
}
69+
70+
/**
71+
* (PHP 5 >= 5.1.0)<br/>
72+
* Constructs the object
73+
* @link http://php.net/manual/en/serializable.unserialize.php
74+
* @see \Serializable::unserialize()
75+
* @param string $serialized The string representation of the object.
76+
* @return void
77+
*/
78+
public function unserialize($serialized)
79+
{
80+
$serialized = unserialize($serialized);
81+
if (is_array($serialized)) {
82+
$reflection = new \ReflectionClass(get_called_class());
83+
foreach ($serialized as $key => $value) {
84+
$property = $reflection->getProperty($key);
85+
$property->setAccessible(true);
86+
$property->setValue($this, $value);
87+
if ($property->isPrivate() || $property->isProtected()) {
88+
$property->setAccessible(false);
89+
}
90+
}
91+
}
92+
}
93+
94+
/**
95+
* @return float
96+
*/
97+
public function getAltitude()
98+
{
99+
return $this->_altitude;
100+
}
101+
102+
/**
103+
* @return float
104+
*/
105+
public function getAltitudePrecision()
106+
{
107+
return $this->_altitudePrecision;
108+
}
109+
110+
/**
111+
* @return float
112+
*/
113+
public function getLatitude()
114+
{
115+
return $this->_latitude;
116+
}
117+
118+
/**
119+
* @return float
120+
*/
121+
public function getLongitude()
122+
{
123+
return $this->_longitude;
124+
}
125+
126+
/**
127+
* @return float
128+
*/
129+
public function getPrecision()
130+
{
131+
return $this->_precision;
132+
}
133+
134+
/**
135+
* @return string
136+
*/
137+
public function getType()
138+
{
139+
return $this->_type;
140+
}
141+
}

0 commit comments

Comments
 (0)