GeocodeLib.php 25 KB

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