GeocodeLib.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. <?php
  2. App::uses('String', 'Utility');
  3. App::uses('HttpSocket', 'Network/Http');
  4. /**
  5. * Geocode via google (UPDATE: api3)
  6. * @see https://developers.google.com/maps/documentation/geocoding/
  7. *
  8. * Used by Tools.GeocoderBehavior
  9. *
  10. * TODOS (since 1.2):
  11. * - Work with exceptions in 2.x
  12. *
  13. * @author Mark Scherer
  14. * @licence MIT
  15. */
  16. class GeocodeLib {
  17. const BASE_URL = 'https://{host}/maps/api/geocode/json?';
  18. const DEFAULT_HOST = 'maps.googleapis.com';
  19. const ACC_COUNTRY = 0;
  20. const ACC_AAL1 = 1;
  21. const ACC_AAL2 = 2;
  22. const ACC_AAL3 = 3;
  23. const ACC_POSTAL = 4;
  24. const ACC_LOC = 5;
  25. const ACC_SUBLOC = 6;
  26. const ACC_ROUTE = 7;
  27. const ACC_INTERSEC = 8;
  28. const ACC_STREET = 9;
  29. const UNIT_KM = 'K';
  30. const UNIT_NAUTICAL = 'N';
  31. const UNIT_FEET = 'F';
  32. const UNIT_INCHES = 'I';
  33. const UNIT_MILES = 'M';
  34. // First tries with curl, then cake, then php
  35. public $use = array(
  36. 'curl' => true,
  37. 'cake' => true,
  38. 'php' => true
  39. );
  40. public $units = array(
  41. self::UNIT_KM => 1.609344,
  42. self::UNIT_NAUTICAL => 0.868976242,
  43. self::UNIT_FEET => 5280,
  44. self::UNIT_INCHES => 63360,
  45. self::UNIT_MILES => 1
  46. );
  47. /**
  48. * Validation and retrieval options
  49. * - use:
  50. * - log: false logs only real errors, true all activities
  51. * - pause: timeout to prevent blocking
  52. * - ...
  53. *
  54. */
  55. public $options = array(
  56. 'log' => false,
  57. 'pause' => 2000000, # in microseconds (2000000 = 2 seconds = recommended by Google)
  58. 'repeat' => 2, # if over limits, how many times to repeat
  59. 'min_accuracy' => self::ACC_COUNTRY,
  60. 'allow_inconclusive' => true,
  61. 'expect' => array(), # see accuracyTypes for details
  62. 'host' => null, # results in maps.google.com - use if you wish to obtain the closest address
  63. );
  64. /**
  65. * Url params
  66. */
  67. public $params = array(
  68. 'address' => '', # either address or latlng required!
  69. 'latlng' => '', # The textual latitude/longitude value for which you wish to obtain the closest, human-readable address
  70. 'region' => '', # The region code, specified as a ccTLD ("top-level domain") two-character
  71. 'language' => 'de',
  72. 'bounds' => '',
  73. 'sensor' => 'false', # device with gps module sensor
  74. //'key' => '' # not necessary anymore
  75. );
  76. public $reachedQueryLimit = false;
  77. protected $error = array();
  78. protected $debug = array();
  79. protected $result = null;
  80. public $statusCodes = array(
  81. self::STATUS_SUCCESS => 'Success',
  82. self::STATUS_BAD_REQUEST => 'Sensor param missing',
  83. self::STATUS_MISSING_QUERY => 'Adress/LatLng missing',
  84. self::STATUS_UNKNOWN_ADDRESS => 'Success, but to address found',
  85. self::STATUS_TOO_MANY_QUERIES => 'Limit exceeded',
  86. );
  87. public $accuracyTypes = array(
  88. self::ACC_COUNTRY => 'country',
  89. self::ACC_AAL1 => 'administrative_area_level_1', # provinces/states
  90. self::ACC_AAL2 => 'administrative_area_level_2 ',
  91. self::ACC_AAL3 => 'administrative_area_level_3',
  92. self::ACC_LOC => 'locality',
  93. self::ACC_POSTAL => 'postal_code',
  94. self::ACC_SUBLOC => 'sublocality',
  95. self::ACC_ROUTE => 'route',
  96. self::ACC_INTERSEC => 'intersection',
  97. self::ACC_STREET => 'street_address',
  98. );
  99. public function __construct($options = array()) {
  100. $this->defaultParams = $this->params;
  101. $this->defaultOptions = $this->options;
  102. if (Configure::read('debug') > 0) {
  103. $this->options['log'] = true;
  104. }
  105. $this->setOptions($options);
  106. if (empty($this->options['host'])) {
  107. $this->options['host'] = static::DEFAULT_HOST;
  108. }
  109. }
  110. /**
  111. * @param array $params
  112. * @return void
  113. */
  114. public function setParams($params) {
  115. foreach ($params as $key => $value) {
  116. if ($key === 'sensor' && $value !== 'false' && $value !== 'true') {
  117. $value = !empty($value) ? 'true' : 'false';
  118. }
  119. $this->params[$key] = (string)$value;
  120. }
  121. }
  122. /**
  123. * @param array $options
  124. * @return void
  125. */
  126. public function setOptions($options) {
  127. foreach ($options as $key => $value) {
  128. $this->options[$key] = $value;
  129. }
  130. }
  131. public function setError($error) {
  132. if (empty($error)) {
  133. return;
  134. }
  135. $this->_setDebug('setError', $error);
  136. $this->error[] = $error;
  137. }
  138. public function error($asString = true, $separator = ', ') {
  139. if (!$asString) {
  140. return $this->error;
  141. }
  142. return implode(', ', $this->error);
  143. }
  144. /**
  145. * Reset - ready for the next request
  146. *
  147. * @param mixed boolean $full or string === 'params' to reset just params
  148. * @return void
  149. */
  150. public function reset($full = true) {
  151. $this->error = array();
  152. $this->result = null;
  153. $this->reachedQueryLimit = false;
  154. if (empty($full)) {
  155. return;
  156. }
  157. if ($full === 'params') {
  158. $this->params = $this->defaultParams;
  159. return;
  160. }
  161. $this->params = $this->defaultParams;
  162. $this->options = $this->defaultOptions;
  163. }
  164. /**
  165. * Build url
  166. *
  167. * @return string url (full)
  168. */
  169. protected function _url() {
  170. $params = array(
  171. 'host' => $this->options['host']
  172. );
  173. $url = String::insert(static::BASE_URL, $params, array('before' => '{', 'after' => '}', 'clean' => true));
  174. return $url;
  175. }
  176. /**
  177. * Seems like there are no inconclusive results anymore...
  178. *
  179. * @return bool isInconclusive (or null if no query has been run yet)
  180. */
  181. public function isInconclusive() {
  182. if ($this->result === null) {
  183. return null;
  184. }
  185. return !empty($this->result['valid_results']) && $this->result['valid_results'] > 1;
  186. }
  187. /**
  188. * Return the geocoder result or empty array on failure
  189. *
  190. * @return array result
  191. */
  192. public function getResult() {
  193. if ($this->result === null) {
  194. return array();
  195. }
  196. return $this->result;
  197. }
  198. /**
  199. * Trying to avoid "TOO_MANY_QUERIES" error
  200. */
  201. public function pause() {
  202. usleep($this->options['pause']);
  203. }
  204. /**
  205. * Actual querying.
  206. * The query will be flatted, and if multiple results are fetched, they will be found
  207. * in $result['all'].
  208. *
  209. * @param string $address
  210. * @param array $params
  211. * @return bool Success
  212. */
  213. public function geocode($address, $params = array()) {
  214. if ($this->reachedQueryLimit) {
  215. $this->setError('Over Query Limit - abort');
  216. return false;
  217. }
  218. $this->reset(false);
  219. $this->_setDebug('geocode', compact('address', 'params'));
  220. $params = array('address' => $address) + $params;
  221. $this->setParams($params);
  222. $count = 0;
  223. $requestUrl = $this->_url();
  224. while (true) {
  225. $result = $this->_fetch($requestUrl, $this->params);
  226. if ($result === false || $result === null) {
  227. $this->setError('Could not retrieve url');
  228. CakeLog::write('geocode', 'Geocoder could not retrieve url with \'' . $address . '\'');
  229. return false;
  230. }
  231. $this->_setDebug('raw', $result);
  232. $result = $this->_transform($result);
  233. if (!is_array($result)) {
  234. $this->setError('Result parsing failed');
  235. CakeLog::write('geocode', __d('tools', 'Failed geocode parsing of \'%s\'', $address));
  236. return false;
  237. }
  238. $status = $result['status'];
  239. if ($status == static::STATUS_SUCCESS) {
  240. if (!$this->_process($result)) {
  241. return false;
  242. }
  243. // save Result
  244. if ($this->options['log']) {
  245. CakeLog::write('geocode', __d('tools', 'Address \'%s\' has been geocoded', $address));
  246. }
  247. break;
  248. } elseif ($status == static::STATUS_TOO_MANY_QUERIES) {
  249. // sent geocodes too fast, delay +0.1 seconds
  250. if ($this->options['log']) {
  251. CakeLog::write('geocode', __d('tools', 'Delay necessary for address \'%s\'', $address));
  252. }
  253. $count++;
  254. } else {
  255. // something went wrong
  256. $errorMessage = (isset($result['error_message']) ? $result['error_message'] : '');
  257. if (empty($errorMessage)) {
  258. $errorMessage = $this->errorMessage($status);
  259. }
  260. if (empty($errorMessage)) {
  261. $errorMessage = 'unknown';
  262. }
  263. $this->setError('Error ' . $status . ' (' . $errorMessage . ')');
  264. if ($this->options['log']) {
  265. CakeLog::write('geocode', __d('tools', 'Could not geocode \'%s\'', $address));
  266. }
  267. return false; # for now...
  268. }
  269. if ($count > $this->options['repeat']) {
  270. if ($this->options['log']) {
  271. CakeLog::write('geocode', __d('tools', 'Aborted after too many trials with \'%s\'', $address));
  272. }
  273. $this->setError('Too many trials - abort');
  274. $this->reachedQueryLimit = true;
  275. return false;
  276. }
  277. $this->pause();
  278. }
  279. return true;
  280. }
  281. /**
  282. * Results usually from most accurate to least accurate result (street_address, ..., country)
  283. *
  284. * @param float $lat
  285. * @param float $lng
  286. * @param array $params
  287. * @return bool Success
  288. */
  289. public function reverseGeocode($lat, $lng, $params = array()) {
  290. if ($this->reachedQueryLimit) {
  291. $this->setError('Over Query Limit - abort');
  292. return false;
  293. }
  294. $this->reset(false);
  295. $this->_setDebug('reverseGeocode', compact('lat', 'lng', 'params'));
  296. $latlng = $lat . ',' . $lng;
  297. $params = array('latlng' => $latlng) + $params;
  298. $this->setParams($params);
  299. $count = 0;
  300. $requestUrl = $this->_url();
  301. while (true) {
  302. $result = $this->_fetch($requestUrl, $this->params);
  303. if ($result === false || $result === null) {
  304. $this->setError('Could not retrieve url');
  305. CakeLog::write('geocode', __d('tools', 'Could not retrieve url with \'%s\'', $latlng));
  306. return false;
  307. }
  308. $this->_setDebug('raw', $result);
  309. $result = $this->_transform($result);
  310. if (!is_array($result)) {
  311. $this->setError('Result parsing failed');
  312. CakeLog::write('geocode', __d('tools', 'Failed reverseGeocode parsing of \'%s\'', $latlng));
  313. return false;
  314. }
  315. $status = $result['status'];
  316. if ($status == static::STATUS_SUCCESS) {
  317. if (!$this->_process($result)) {
  318. return false;
  319. }
  320. // save Result
  321. if ($this->options['log']) {
  322. CakeLog::write('geocode', __d('tools', 'Address \'%s\' has been geocoded', $latlng));
  323. }
  324. break;
  325. } elseif ($status == static::STATUS_TOO_MANY_QUERIES) {
  326. // sent geocodes too fast, delay +0.1 seconds
  327. if ($this->options['log']) {
  328. CakeLog::write('geocode', __d('tools', 'Delay necessary for \'%s\'', $latlng));
  329. }
  330. $count++;
  331. } else {
  332. // something went wrong
  333. $this->setError('Error ' . $status . (isset($this->statusCodes[$status]) ? ' (' . $this->statusCodes[$status] . ')' : ''));
  334. if ($this->options['log']) {
  335. CakeLog::write('geocode', __d('tools', 'Could not geocode \'%s\'', $latlng));
  336. }
  337. return false; # for now...
  338. }
  339. if ($count > $this->options['repeat']) {
  340. if ($this->options['log']) {
  341. CakeLog::write('geocode', __d('tools', 'Aborted after too many trials with \'%s\'', $latlng));
  342. }
  343. $this->setError(__d('tools', 'Too many trials - abort'));
  344. $this->reachedQueryLimit = true;
  345. return false;
  346. }
  347. $this->pause();
  348. }
  349. return true;
  350. }
  351. /**
  352. * GeocodeLib::_process()
  353. *
  354. * @param mixed $result
  355. * @return bool Success
  356. */
  357. protected function _process($result) {
  358. $this->result = null;
  359. $validResults = 0;
  360. foreach ($result['results'] as $res) {
  361. if (!$res['valid_type']) {
  362. continue;
  363. }
  364. $validResults++;
  365. if (isset($this->result)) {
  366. continue;
  367. }
  368. $this->result = $res;
  369. }
  370. // Only necessary for allow_inconclusive and no valid results found
  371. if (!$this->result && !empty($result['results'])) {
  372. $this->result = $result['results'][0];
  373. }
  374. $this->result['valid_results'] = $validResults;
  375. $this->result['all'] = $result['results'];
  376. // validate
  377. if (!$this->options['allow_inconclusive'] && $validResults === 0) {
  378. $this->setError(__d('tools', 'No results found'));
  379. return false;
  380. }
  381. if (!$this->options['allow_inconclusive'] && $validResults > 1) {
  382. $this->setError(__d('tools', 'Inconclusive result (total of %s)', $validResults));
  383. return false;
  384. }
  385. if ($this->_isNotAccurateEnough($this->result['accuracy'])) {
  386. $minAccuracy = $this->accuracyTypes[$this->options['min_accuracy']];
  387. $this->setError(__d('tools', 'Accuracy not good enough (%s instead of at least %s)', $this->result['accuracy_name'], $minAccuracy));
  388. return false;
  389. }
  390. if (!empty($this->options['expect'])) {
  391. $expected = (array)$this->options['expect'];
  392. foreach ($expected as $k => $v) {
  393. $accuracy = is_int($v) ? $this->accuracyTypes[$v] : $v;
  394. $expected[$k] = $accuracy;
  395. }
  396. $found = array_intersect($this->result['types'], $expected);
  397. $validExpectation = !empty($found);
  398. if (!$validExpectation) {
  399. $this->setError(__d('tools', 'Expectation not reached (we have %s instead of at least one of %s)',
  400. implode(', ', $found),
  401. implode(', ', $expected)
  402. ));
  403. return false;
  404. }
  405. }
  406. return true;
  407. }
  408. /**
  409. * GeocodeLib::accuracyTypes()
  410. *
  411. * @param mixed $value
  412. * @return mixed Type or types
  413. */
  414. public function accuracyTypes($value = null) {
  415. if ($value !== null) {
  416. if (isset($this->accuracyTypes[$value])) {
  417. return $this->accuracyTypes[$value];
  418. }
  419. return null;
  420. }
  421. return $this->accuracyTypes;
  422. }
  423. protected function _validate($result) {
  424. $validType = false;
  425. foreach ($result['types'] as $type) {
  426. if (in_array($type, $this->accuracyTypes, true)) {
  427. $validType = true;
  428. break;
  429. }
  430. }
  431. $result['valid_type'] = $validType;
  432. return $result;
  433. }
  434. protected function _accuracy($result) {
  435. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  436. $accuracy = 0;
  437. foreach ($accuracyTypes as $key => $field) {
  438. if (array_key_exists($field, $result) && !empty($result[$field])) {
  439. $accuracy = $key;
  440. break;
  441. }
  442. }
  443. $result['accuracy'] = $accuracy;
  444. $result['accuracy_name'] = $this->accuracyTypes[$accuracy];
  445. return $result;
  446. }
  447. /**
  448. * @param int $accuracy
  449. * @return bool notAccurateEnough
  450. */
  451. protected function _isNotAccurateEnough($accuracy) {
  452. if (!array_key_exists($accuracy, $this->accuracyTypes)) {
  453. $accuracy = 0;
  454. }
  455. // is our current accuracy < minimum?
  456. return $accuracy < $this->options['min_accuracy'];
  457. }
  458. /**
  459. * GeocodeLib::_transform()
  460. *
  461. * @param string|array $record JSON string or array
  462. * @return array
  463. */
  464. protected function _transform($record) {
  465. if (!is_array($record)) {
  466. $record = json_decode($record, true);
  467. }
  468. if (empty($record['results'])) {
  469. $record['results'] = array();
  470. return $record;
  471. }
  472. $record['results'] = $this->_transformData($record['results']);
  473. return $record;
  474. }
  475. /**
  476. * Try to find the max accuracy level
  477. * - look through all fields and
  478. * attempt to find the first record which matches an accuracyTypes field
  479. *
  480. * @param array $record
  481. * @return int|null $maxAccuracy 9-0 as defined in $this->accuracyTypes
  482. */
  483. protected function _getMaxAccuracy($record) {
  484. if (!is_array($record)) {
  485. return null;
  486. }
  487. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  488. foreach ($accuracyTypes as $key => $field) {
  489. if (array_key_exists($field, $record) && !empty($record[$field])) {
  490. // found $field -- return it's $key
  491. return $key;
  492. }
  493. }
  494. // not found? recurse into all possible children
  495. foreach (array_keys($record) as $key) {
  496. if (empty($record[$key]) || !is_array($record[$key])) {
  497. continue;
  498. }
  499. $accuracy = $this->_getMaxAccuracy($record[$key]);
  500. if ($accuracy !== null) {
  501. // found in nested value
  502. return $accuracy;
  503. }
  504. }
  505. return null;
  506. }
  507. /**
  508. * Flattens result array and returns clean record
  509. * keys:
  510. * - formatted_address, type, country, country_code, country_province, country_province_code, locality, sublocality, postal_code, route, lat, lng, location_type, viewport, bounds
  511. *
  512. * @param mixed $record any level of input, whole raw array or records or single record
  513. * @return array record organized & normalized
  514. */
  515. protected function _transformData($record) {
  516. if (!is_array($record)) {
  517. return array();
  518. }
  519. if (!array_key_exists('address_components', $record)) {
  520. foreach (array_keys($record) as $key) {
  521. $record[$key] = $this->_transformData($record[$key]);
  522. }
  523. return $record;
  524. }
  525. $res = array();
  526. // handle and organize address_components
  527. $components = array();
  528. foreach ($record['address_components'] as $c) {
  529. $type = $c['types'][0];
  530. $types = $c['types'];
  531. if (array_key_exists($type, $components)) {
  532. $components[$type]['name'] .= ' ' . $c['long_name'];
  533. $components[$type]['abbr'] .= ' ' . $c['short_name'];
  534. $components[$type]['types'] += $types;
  535. } else {
  536. $components[$type] = array('name' => $c['long_name'], 'abbr' => $c['short_name'], 'types' => $types);
  537. }
  538. }
  539. $res['formatted_address'] = $record['formatted_address'];
  540. if (array_key_exists('country', $components)) {
  541. $res['country'] = $components['country']['name'];
  542. $res['country_code'] = $components['country']['abbr'];
  543. } else {
  544. $res['country'] = $res['country_code'] = '';
  545. }
  546. if (array_key_exists('administrative_area_level_1', $components)) {
  547. $res['country_province'] = $components['administrative_area_level_1']['name'];
  548. $res['country_province_code'] = $components['administrative_area_level_1']['abbr'];
  549. } else {
  550. $res['country_province'] = $res['country_province_code'] = '';
  551. }
  552. if (array_key_exists('postal_code', $components)) {
  553. $res['postal_code'] = $components['postal_code']['name'];
  554. } else {
  555. $res['postal_code'] = '';
  556. }
  557. if (array_key_exists('locality', $components)) {
  558. $res['locality'] = $components['locality']['name'];
  559. } else {
  560. $res['locality'] = '';
  561. }
  562. if (array_key_exists('sublocality', $components)) {
  563. $res['sublocality'] = $components['sublocality']['name'];
  564. } else {
  565. $res['sublocality'] = '';
  566. }
  567. if (array_key_exists('route', $components)) {
  568. $res['route'] = $components['route']['name'];
  569. if (array_key_exists('street_number', $components)) {
  570. $res['route'] .= ' ' . $components['street_number']['name'];
  571. }
  572. } else {
  573. $res['route'] = '';
  574. }
  575. // determine accuracy types
  576. if (array_key_exists('types', $record)) {
  577. $res['types'] = $record['types'];
  578. } else {
  579. $res['types'] = array();
  580. }
  581. //TODO: add more
  582. $res['lat'] = $record['geometry']['location']['lat'];
  583. $res['lng'] = $record['geometry']['location']['lng'];
  584. $res['location_type'] = $record['geometry']['location_type'];
  585. if (!empty($record['geometry']['viewport'])) {
  586. $res['viewport'] = array('sw' => $record['geometry']['viewport']['southwest'], 'ne' => $record['geometry']['viewport']['northeast']);
  587. }
  588. if (!empty($record['geometry']['bounds'])) {
  589. $res['bounds'] = array('sw' => $record['geometry']['bounds']['southwest'], 'ne' => $record['geometry']['bounds']['northeast']);
  590. }
  591. // manuell corrections
  592. $array = array(
  593. 'Berlin' => 'BE',
  594. );
  595. if (!empty($res['country_province_code']) && array_key_exists($res['country_province_code'], $array)) {
  596. $res['country_province_code'] = $array[$res['country_province_code']];
  597. }
  598. if (!empty($record['postcode_localities'])) {
  599. $res['postcode_localities'] = $record['postcode_localities'];
  600. }
  601. if (!empty($record['address_components'])) {
  602. $res['address_components'] = $record['address_components'];
  603. }
  604. $res = $this->_validate($res);
  605. $res = $this->_accuracy($res);
  606. return $res;
  607. }
  608. /**
  609. * Fetches url with curl if available
  610. * fallbacks: cake and php
  611. * note: expects url with json encoded content
  612. *
  613. * @return mixed
  614. **/
  615. protected function _fetch($url, $query) {
  616. $this->HttpSocket = new HttpSocket();
  617. foreach ($query as $k => $v) {
  618. if ($v === '') {
  619. unset($query[$k]);
  620. }
  621. }
  622. if ($res = $this->HttpSocket->get($url, $query)) {
  623. return $res->body;
  624. }
  625. $errorCode = $this->HttpSocket->response->code;
  626. $this->setError('Error '. $errorCode. ': ' . $this->errorMessage($errorCode));
  627. return false;
  628. }
  629. /**
  630. * return debugging info
  631. *
  632. * @return array debug
  633. */
  634. public function debug() {
  635. $this->debug['result'] = $this->result;
  636. return $this->debug;
  637. }
  638. /**
  639. * set debugging info
  640. *
  641. * @param string $key
  642. * @param mixed $data
  643. * @return void
  644. */
  645. public function _setDebug($key, $data = null) {
  646. $this->debug[$key] = $data;
  647. }
  648. /**
  649. * Calculates Distance between two points - each: array('lat'=>x,'lng'=>y)
  650. * DB:
  651. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  652. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  653. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  654. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  655. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  656. 'AS distance'
  657. *
  658. * @param array pointX
  659. * @param array pointY
  660. * @param string $unit Unit char or constant (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet)
  661. * @return int Distance in km
  662. */
  663. public function distance(array $pointX, array $pointY, $unit = null) {
  664. if (empty($unit)) {
  665. $unit = array_keys($this->units);
  666. $unit = $unit[0];
  667. }
  668. $unit = strtoupper($unit);
  669. if (!isset($this->units[$unit])) {
  670. throw new CakeException(sprintf('Invalid Unit: %s', $unit));
  671. }
  672. $res = $this->calculateDistance($pointX, $pointY);
  673. if (isset($this->units[$unit])) {
  674. $res *= $this->units[$unit];
  675. }
  676. return ceil($res);
  677. }
  678. /**
  679. * GeocodeLib::calculateDistance()
  680. *
  681. * @param array $pointX
  682. * @param array $pointY
  683. * @return float
  684. */
  685. public static function calculateDistance(array $pointX, array $pointY) {
  686. /*
  687. $res = 6371.04 * ACOS( COS( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  688. COS( PI()/2 - rad2deg(90 - $pointY['lat'])) *
  689. COS( rad2deg($pointX['lng']) - rad2deg($pointY['lng'])) +
  690. SIN( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  691. SIN( PI()/2 - rad2deg(90 - $pointY['lat'])));
  692. $res = 6371.04 * acos(sin($pointY['lat'])*sin($pointX['lat'])+cos($pointY['lat'])*cos($pointX['lat'])*cos($pointY['lng'] - $pointX['lng']));
  693. */
  694. // seems to be the only working one (although slightly incorrect...)
  695. $res = 69.09 * rad2deg(acos(sin(deg2rad($pointX['lat'])) * sin(deg2rad($pointY['lat'])) + cos(deg2rad($pointX['lat'])) * cos(deg2rad($pointY['lat'])) * cos(deg2rad($pointX['lng'] - $pointY['lng']))));
  696. return $res;
  697. }
  698. /**
  699. * Convert between units
  700. *
  701. * @param float $value
  702. * @param string $fromUnit (using class constants)
  703. * @param string $toUnit (using class constants)
  704. * @return float convertedValue
  705. * @throws CakeException
  706. */
  707. public function convert($value, $fromUnit, $toUnit) {
  708. if (!isset($this->units[($fromUnit = strtoupper($fromUnit))]) || !isset($this->units[($toUnit = strtoupper($toUnit))])) {
  709. throw new CakeException('Invalid Unit');
  710. }
  711. if ($fromUnit === 'M') {
  712. $value *= $this->units[$toUnit];
  713. } elseif ($toUnit === 'M') {
  714. $value /= $this->units[$fromUnit];
  715. } else {
  716. $value /= $this->units[$fromUnit];
  717. $value *= $this->units[$toUnit];
  718. }
  719. return $value;
  720. }
  721. /**
  722. * Fuzziness filter for coordinates (lat or lng).
  723. * Useful if you store other users' locations and want to grant some
  724. * privacy protection. This way the coordinates will be slightly modified.
  725. *
  726. * @param float coord Coordinates
  727. * @param int level The Level of blurness (0 = nothing to 5 = extrem)
  728. * - 1:
  729. * - 2:
  730. * - 3:
  731. * - 4:
  732. * - 5:
  733. * @return float Coordinates
  734. * @throws CakeException
  735. */
  736. public static function blur($coord, $level = 0) {
  737. if (!$level) {
  738. return $coord;
  739. }
  740. //TODO:
  741. switch ($level) {
  742. case 1:
  743. break;
  744. case 2:
  745. break;
  746. case 3:
  747. break;
  748. case 4:
  749. break;
  750. case 5:
  751. break;
  752. default:
  753. throw new CakeException(sprintf('Invalid level \'%s\'', $level));
  754. }
  755. $scrambleVal = 0.000001 * mt_rand(1000, 2000) * (mt_rand(0, 1) === 0 ? 1 : -1);
  756. return ($coord + $scrambleVal);
  757. //$scrambleVal *= (mt_rand(0,1) === 0 ? 1 : 2);
  758. //$scrambleVal *= (float)(2^$level);
  759. // TODO: + - by chance!!!
  760. return $coord + $scrambleVal;
  761. }
  762. const TYPE_ROOFTOP = 'ROOFTOP';
  763. const TYPE_RANGE_INTERPOLATED = 'RANGE_INTERPOLATED';
  764. const TYPE_GEOMETRIC_CENTER = 'GEOMETRIC_CENTER';
  765. const TYPE_APPROXIMATE = 'APPROXIMATE';
  766. /**
  767. * Return human error message string for response code of Geocoder API.
  768. *
  769. * @param mixed $code
  770. * @return string
  771. */
  772. public function statusMessage($code) {
  773. if (isset($this->statusCodes[$code])) {
  774. return __d('tools', $this->statusCodes[$code]);
  775. }
  776. return '';
  777. }
  778. const STATUS_SUCCESS = 'OK'; //200;
  779. const STATUS_TOO_MANY_QUERIES = 'OVER_QUERY_LIMIT'; //620;
  780. const STATUS_BAD_REQUEST = 'REQUEST_DENIED'; //400;
  781. const STATUS_MISSING_QUERY = 'INVALID_REQUEST';//601;
  782. const STATUS_UNKNOWN_ADDRESS = 'ZERO_RESULTS'; //602;
  783. /**
  784. * Return human error message string for error code of HttpSocket response.
  785. *
  786. * @param mixed $code
  787. * @return string
  788. */
  789. public function errorMessage($code) {
  790. $codes = array(
  791. static::CODE_SUCCESS => 'Success',
  792. static::CODE_BAD_REQUEST => 'Bad Request',
  793. static::CODE_MISSING_ADDRESS => 'Bad Address',
  794. static::CODE_UNKNOWN_ADDRESS => 'Unknown Address',
  795. static::CODE_UNAVAILABLE_ADDRESS => 'Unavailable Address',
  796. static::CODE_BAD_KEY => 'Bad Key',
  797. static::CODE_TOO_MANY_QUERIES => 'Too Many Queries',
  798. );
  799. if (isset($codes[$code])) {
  800. return __d('tools', $codes[$code]);
  801. }
  802. return '';
  803. }
  804. const CODE_SUCCESS = 200;
  805. const CODE_BAD_REQUEST = 400;
  806. const CODE_SERVER_ERROR = 500;
  807. const CODE_MISSING_ADDRESS = 601;
  808. const CODE_UNKNOWN_ADDRESS = 602;
  809. const CODE_UNAVAILABLE_ADDRESS = 603;
  810. const CODE_UNKNOWN_DIRECTIONS = 604;
  811. const CODE_BAD_KEY = 610;
  812. const CODE_TOO_MANY_QUERIES = 620;
  813. }
  814. /*
  815. TODO:
  816. http://code.google.com/intl/de-DE/apis/maps/documentation/geocoding/
  817. - whats the difference to "http://maps.google.com/maps/api/geocode/output?parameters"
  818. */