api.maponapi.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. <?php
  2. /**
  3. * Mapon cars GPS location service low-level api
  4. */
  5. class MaponAPI {
  6. /**
  7. * @var string Your API key
  8. */
  9. public $apiKey;
  10. /**
  11. * @var string API URL, with trailing slash
  12. */
  13. public $apiUrl;
  14. public $libVersion = 1.0;
  15. public $debug = false;
  16. /**
  17. * @param string $apiKey Your API key
  18. * @param string $apiUrl Your API url, with trailing slash
  19. */
  20. public function __construct($apiKey, $apiUrl) {
  21. $this->apiKey = $apiKey;
  22. $this->apiUrl = rtrim($apiUrl, '/') . '/';
  23. }
  24. /**
  25. * @param string $requestMethod
  26. * @param string $apiMethod
  27. * @param array $getData
  28. * @param array $postData
  29. * @return stdClass
  30. * @throws ApiException
  31. */
  32. public function callMethod($requestMethod, $apiMethod, $getData = array(), $postData = array()) {
  33. if (!function_exists('json_decode')) {
  34. throw new ApiException('Please enable php json extension');
  35. }
  36. $getData += array(
  37. 'key' => $this->apiKey,
  38. '_phplibv' => $this->libVersion,
  39. );
  40. $url = $this->apiUrl . $apiMethod . '.json';
  41. $res = $this->getUrlContent($url, $requestMethod, $getData, $postData);
  42. $json = json_decode($res);
  43. if (is_null($json) || (!isset($json->data) && !isset($json->error))) {
  44. if ($this->debug) {
  45. echo "Response from API:\n" . $res . "\n";
  46. }
  47. throw new ApiException('Error while parsing API response');
  48. }
  49. if (isset($json->error)) {
  50. throw new ApiException($json->error->msg, $json->error->code);
  51. }
  52. return $json;
  53. }
  54. /**
  55. * @param string $urlDomain Domain + path WITHOUT query part
  56. * @param string $requestMethod get or post
  57. * @param array $queryData
  58. * @param array $postData
  59. * @return mixed
  60. * @throws ApiException
  61. */
  62. private function getUrlContent($urlDomain, $requestMethod, array $queryData = array(), array $postData = array()) {
  63. $isPost = $requestMethod == 'post';
  64. $urlDomain .= '?' . http_build_query($queryData);
  65. $ch = curl_init();
  66. curl_setopt($ch, CURLOPT_URL, $urlDomain);
  67. curl_setopt($ch, CURLOPT_POST, $isPost ? 1 : 0);
  68. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  69. if ($isPost) {
  70. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
  71. }
  72. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  73. $output = curl_exec($ch);
  74. $error = curl_error($ch);
  75. curl_close($ch);
  76. if (!$output) {
  77. throw new ApiException('Could not HTTP request: ' . var_export($error, true));
  78. }
  79. return $output;
  80. }
  81. /**
  82. * Call GET API request
  83. *
  84. * @param string $action Class and action, for example, unit/list
  85. * @param array $queryData Data which will be passed as GET parameters
  86. * @return stdClass
  87. * @throws ApiException
  88. */
  89. public function get($action, $queryData = array()) {
  90. return $this->callMethod('get', $action, $queryData);
  91. }
  92. /**
  93. * Call POST API request
  94. *
  95. * @param $action Class and action, for example, object/save
  96. * @param array $postData Data which will be passed as POST data
  97. * @return stdClass
  98. * @throws ApiException
  99. */
  100. public function post($action, $postData = array()) {
  101. return $this->callMethod('post', $action, array(), $postData);
  102. }
  103. /**
  104. * Decodes encoded route polyline and returns lat/lng array.
  105. * If $speed string is given, then return array will also contain velocity for each coordinate.
  106. * If $start_time is given then each coordinate will also contain time.
  107. * All this information can be obtained by actions which return route data.
  108. *
  109. * Based on:
  110. * http://code.google.com/apis/maps/documentation/polylinealgorithm.html
  111. *
  112. * @param string $encoded Encoded route
  113. * @param string $speed Encoded speed
  114. * @param integer $startTime Route start time in unix timestamp
  115. * @return array
  116. */
  117. public function decodePolyline($encoded, $speed = null, $startTime = null) {
  118. if (!is_null($speed)) {
  119. $speed = $this->decodeSpeed($speed);
  120. }
  121. $length = strlen($encoded);
  122. $index = 0;
  123. $points = array();
  124. $lat = 0;
  125. $lng = 0;
  126. while ($index < $length) {
  127. // Temporary variable to hold each ASCII byte.
  128. $b = 0;
  129. // The encoded polyline consists of a latitude value followed by a
  130. // longitude value. They should always come in pairs. Read the
  131. // latitude value first.
  132. $shift = 0;
  133. $result = 0;
  134. do {
  135. // The `ord(substr($encoded, $index++))` statement returns the ASCII
  136. // code for the character at $index. Subtract 63 to get the original
  137. // value. (63 was added to ensure proper ASCII characters are displayed
  138. // in the encoded polyline string, which is `human` readable)
  139. $b = ord(substr($encoded, $index++)) - 63;
  140. // AND the bits of the byte with 0x1f to get the original 5-bit `chunk.
  141. // Then left shift the bits by the required amount, which increases
  142. // by 5 bits each time.
  143. // OR the value into $results, which sums up the individual 5-bit chunks
  144. // into the original value. Since the 5-bit chunks were reversed in
  145. // order during encoding, reading them in this way ensures proper
  146. // summation.
  147. $result |= ($b & 0x1f) << $shift;
  148. $shift += 5;
  149. }
  150. // Continue while the read byte is >= 0x20 since the last `chunk`
  151. // was not OR'd with 0x20 during the conversion process. (Signals the end)
  152. while ($b >= 0x20);
  153. // Check if negative, and convert. (All negative values have the last bit
  154. // set)
  155. $dlat = (($result & 1) ? ~($result >> 1) : ($result >> 1));
  156. // Compute actual latitude since value is offset from previous value.
  157. $lat += $dlat;
  158. // The next values will correspond to the longitude for this point.
  159. $shift = 0;
  160. $result = 0;
  161. do {
  162. $b = ord(substr($encoded, $index++)) - 63;
  163. $result |= ($b & 0x1f) << $shift;
  164. $shift += 5;
  165. } while ($b >= 0x20);
  166. $dlng = (($result & 1) ? ~($result >> 1) : ($result >> 1));
  167. $lng += $dlng;
  168. // The actual latitude and longitude values were multiplied by
  169. // 1e5 before encoding so that they could be converted to a 32-bit
  170. // integer representation. (With a decimal accuracy of 5 places)
  171. // Convert back to original values.
  172. $points[] = array(
  173. 'lat' => $lat * 1e-5,
  174. 'lng' => $lng * 1e-5
  175. );
  176. }
  177. if (!is_null($speed)) {
  178. foreach ($speed as $k => $v) {
  179. $points[$k]['speed'] = $v[1];
  180. if (!is_null($startTime)) {
  181. $startTime += $v[0];
  182. $points[$k]['time'] = $startTime;
  183. }
  184. }
  185. }
  186. return $points;
  187. }
  188. /**
  189. * decodes time offsets and speeds
  190. * @param string $str
  191. * @return array
  192. */
  193. public function decodeSpeed($str) {
  194. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
  195. $points = strlen($str) / 4;
  196. $data = array();
  197. for ($i = 0; $i < $points; $i++) {
  198. $pos = $i * 4;
  199. $offset = strpos($chars, $str[$pos]) * 64;
  200. $offset += strpos($chars, $str[$pos + 1]);
  201. $speed = strpos($chars, $str[$pos + 2]) * 64;
  202. $speed += strpos($chars, $str[$pos + 3]);
  203. $data[] = array($offset, $speed);
  204. }
  205. return $data;
  206. }
  207. }
  208. /**
  209. * Nothing to see here
  210. */
  211. class ApiException extends \Exception {
  212. }