GeocodeLib.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. $this->result['valid_results'] = $validResults;
  371. $this->result['all'] = $result['results'];
  372. // validate
  373. if (!$this->options['allow_inconclusive'] && $validResults > 1) {
  374. $this->setError(__d('tools', 'Inconclusive result (total of %s)', $validResults));
  375. return false;
  376. }
  377. if ($this->_isNotAccurateEnough($this->result['accuracy'])) {
  378. $minAccuracy = $this->accuracyTypes[$this->options['min_accuracy']];
  379. $this->setError(__d('tools', 'Accuracy not good enough (%s instead of at least %s)', $this->result['accuracy_name'], $minAccuracy));
  380. return false;
  381. }
  382. if (!empty($this->options['expect'])) {
  383. $expected = (array)$this->options['expect'];
  384. foreach ($expected as $k => $v) {
  385. $accuracy = is_int($v) ? $this->accuracyTypes[$v] : $v;
  386. $expected[$k] = $accuracy;
  387. }
  388. $found = array_intersect($this->result['types'], $expected);
  389. $validExpectation = !empty($found);
  390. if (!$validExpectation) {
  391. $this->setError(__d('tools', 'Expectation not reached (we have %s instead of at least one of %s)',
  392. implode(', ', $found),
  393. implode(', ', $expected)
  394. ));
  395. return false;
  396. }
  397. }
  398. return true;
  399. }
  400. /**
  401. * GeocodeLib::accuracyTypes()
  402. *
  403. * @param mixed $value
  404. * @return mixed Type or types
  405. */
  406. public function accuracyTypes($value = null) {
  407. if ($value !== null) {
  408. if (isset($this->accuracyTypes[$value])) {
  409. return $this->accuracyTypes[$value];
  410. }
  411. return null;
  412. }
  413. return $this->accuracyTypes;
  414. }
  415. protected function _validate($result) {
  416. $validType = false;
  417. foreach ($result['types'] as $type) {
  418. if (in_array($type, $this->accuracyTypes, true)) {
  419. $validType = true;
  420. break;
  421. }
  422. }
  423. $result['valid_type'] = $validType;
  424. return $result;
  425. }
  426. protected function _accuracy($result) {
  427. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  428. $accuracy = 0;
  429. foreach ($accuracyTypes as $key => $field) {
  430. if (array_key_exists($field, $result) && !empty($result[$field])) {
  431. $accuracy = $key;
  432. break;
  433. }
  434. }
  435. $result['accuracy'] = $accuracy;
  436. $result['accuracy_name'] = $this->accuracyTypes[$accuracy];
  437. return $result;
  438. }
  439. /**
  440. * @param int $accuracy
  441. * @return bool notAccurateEnough
  442. */
  443. protected function _isNotAccurateEnough($accuracy) {
  444. if (!array_key_exists($accuracy, $this->accuracyTypes)) {
  445. $accuracy = 0;
  446. }
  447. // is our current accuracy < minimum?
  448. return $accuracy < $this->options['min_accuracy'];
  449. }
  450. /**
  451. * GeocodeLib::_transform()
  452. *
  453. * @param string|array $record JSON string or array
  454. * @return array
  455. */
  456. protected function _transform($record) {
  457. if (!is_array($record)) {
  458. $record = json_decode($record, true);
  459. }
  460. if (empty($record['results'])) {
  461. $record['results'] = array();
  462. return $record;
  463. }
  464. $record['results'] = $this->_transformData($record['results']);
  465. return $record;
  466. }
  467. /**
  468. * Try to find the max accuracy level
  469. * - look through all fields and
  470. * attempt to find the first record which matches an accuracyTypes field
  471. *
  472. * @param array $record
  473. * @return int|null $maxAccuracy 9-0 as defined in $this->accuracyTypes
  474. */
  475. protected function _getMaxAccuracy($record) {
  476. if (!is_array($record)) {
  477. return null;
  478. }
  479. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  480. foreach ($accuracyTypes as $key => $field) {
  481. if (array_key_exists($field, $record) && !empty($record[$field])) {
  482. // found $field -- return it's $key
  483. return $key;
  484. }
  485. }
  486. // not found? recurse into all possible children
  487. foreach (array_keys($record) as $key) {
  488. if (empty($record[$key]) || !is_array($record[$key])) {
  489. continue;
  490. }
  491. $accuracy = $this->_getMaxAccuracy($record[$key]);
  492. if ($accuracy !== null) {
  493. // found in nested value
  494. return $accuracy;
  495. }
  496. }
  497. return null;
  498. }
  499. /**
  500. * Flattens result array and returns clean record
  501. * keys:
  502. * - formatted_address, type, country, country_code, country_province, country_province_code, locality, sublocality, postal_code, route, lat, lng, location_type, viewport, bounds
  503. *
  504. * @param mixed $record any level of input, whole raw array or records or single record
  505. * @return array record organized & normalized
  506. */
  507. protected function _transformData($record) {
  508. if (!is_array($record)) {
  509. return array();
  510. }
  511. if (!array_key_exists('address_components', $record)) {
  512. foreach (array_keys($record) as $key) {
  513. $record[$key] = $this->_transformData($record[$key]);
  514. }
  515. return $record;
  516. }
  517. $res = array();
  518. // handle and organize address_components
  519. $components = array();
  520. foreach ($record['address_components'] as $c) {
  521. $type = $c['types'][0];
  522. $types = $c['types'];
  523. if (array_key_exists($type, $components)) {
  524. $components[$type]['name'] .= ' ' . $c['long_name'];
  525. $components[$type]['abbr'] .= ' ' . $c['short_name'];
  526. $components[$type]['types'] += $types;
  527. } else {
  528. $components[$type] = array('name' => $c['long_name'], 'abbr' => $c['short_name'], 'types' => $types);
  529. }
  530. }
  531. $res['formatted_address'] = $record['formatted_address'];
  532. if (array_key_exists('country', $components)) {
  533. $res['country'] = $components['country']['name'];
  534. $res['country_code'] = $components['country']['abbr'];
  535. } else {
  536. $res['country'] = $res['country_code'] = '';
  537. }
  538. if (array_key_exists('administrative_area_level_1', $components)) {
  539. $res['country_province'] = $components['administrative_area_level_1']['name'];
  540. $res['country_province_code'] = $components['administrative_area_level_1']['abbr'];
  541. } else {
  542. $res['country_province'] = $res['country_province_code'] = '';
  543. }
  544. if (array_key_exists('postal_code', $components)) {
  545. $res['postal_code'] = $components['postal_code']['name'];
  546. } else {
  547. $res['postal_code'] = '';
  548. }
  549. if (array_key_exists('locality', $components)) {
  550. $res['locality'] = $components['locality']['name'];
  551. } else {
  552. $res['locality'] = '';
  553. }
  554. if (array_key_exists('sublocality', $components)) {
  555. $res['sublocality'] = $components['sublocality']['name'];
  556. } else {
  557. $res['sublocality'] = '';
  558. }
  559. if (array_key_exists('route', $components)) {
  560. $res['route'] = $components['route']['name'];
  561. if (array_key_exists('street_number', $components)) {
  562. $res['route'] .= ' ' . $components['street_number']['name'];
  563. }
  564. } else {
  565. $res['route'] = '';
  566. }
  567. // determine accuracy types
  568. if (array_key_exists('types', $record)) {
  569. $res['types'] = $record['types'];
  570. } else {
  571. $res['types'] = array();
  572. }
  573. //TODO: add more
  574. $res['lat'] = $record['geometry']['location']['lat'];
  575. $res['lng'] = $record['geometry']['location']['lng'];
  576. $res['location_type'] = $record['geometry']['location_type'];
  577. if (!empty($record['geometry']['viewport'])) {
  578. $res['viewport'] = array('sw' => $record['geometry']['viewport']['southwest'], 'ne' => $record['geometry']['viewport']['northeast']);
  579. }
  580. if (!empty($record['geometry']['bounds'])) {
  581. $res['bounds'] = array('sw' => $record['geometry']['bounds']['southwest'], 'ne' => $record['geometry']['bounds']['northeast']);
  582. }
  583. // manuell corrections
  584. $array = array(
  585. 'Berlin' => 'BE',
  586. );
  587. if (!empty($res['country_province_code']) && array_key_exists($res['country_province_code'], $array)) {
  588. $res['country_province_code'] = $array[$res['country_province_code']];
  589. }
  590. if (!empty($record['postcode_localities'])) {
  591. $res['postcode_localities'] = $record['postcode_localities'];
  592. }
  593. if (!empty($record['address_components'])) {
  594. $res['address_components'] = $record['address_components'];
  595. }
  596. $res = $this->_validate($res);
  597. $res = $this->_accuracy($res);
  598. return $res;
  599. }
  600. /**
  601. * Fetches url with curl if available
  602. * fallbacks: cake and php
  603. * note: expects url with json encoded content
  604. *
  605. * @return mixed
  606. **/
  607. protected function _fetch($url, $query) {
  608. $this->HttpSocket = new HttpSocket();
  609. foreach ($query as $k => $v) {
  610. if ($v === '') {
  611. unset($query[$k]);
  612. }
  613. }
  614. if ($res = $this->HttpSocket->get($url, $query)) {
  615. return $res->body;
  616. }
  617. $errorCode = $this->HttpSocket->response->code;
  618. $this->setError('Error '. $errorCode. ': ' . $this->errorMessage($errorCode));
  619. return false;
  620. }
  621. /**
  622. * return debugging info
  623. *
  624. * @return array debug
  625. */
  626. public function debug() {
  627. $this->debug['result'] = $this->result;
  628. return $this->debug;
  629. }
  630. /**
  631. * set debugging info
  632. *
  633. * @param string $key
  634. * @param mixed $data
  635. * @return void
  636. */
  637. public function _setDebug($key, $data = null) {
  638. $this->debug[$key] = $data;
  639. }
  640. /**
  641. * Calculates Distance between two points - each: array('lat'=>x,'lng'=>y)
  642. * DB:
  643. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  644. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  645. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  646. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  647. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  648. 'AS distance'
  649. *
  650. * @param array pointX
  651. * @param array pointY
  652. * @param string $unit Unit char or constant (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet)
  653. * @return int Distance in km
  654. */
  655. public function distance(array $pointX, array $pointY, $unit = null) {
  656. if (empty($unit)) {
  657. $unit = array_keys($this->units);
  658. $unit = $unit[0];
  659. }
  660. $unit = strtoupper($unit);
  661. if (!isset($this->units[$unit])) {
  662. throw new CakeException(sprintf('Invalid Unit: %s', $unit));
  663. }
  664. $res = $this->calculateDistance($pointX, $pointY);
  665. if (isset($this->units[$unit])) {
  666. $res *= $this->units[$unit];
  667. }
  668. return ceil($res);
  669. }
  670. /**
  671. * GeocodeLib::calculateDistance()
  672. *
  673. * @param array $pointX
  674. * @param array $pointY
  675. * @return float
  676. */
  677. public static function calculateDistance(array $pointX, array $pointY) {
  678. /*
  679. $res = 6371.04 * ACOS( COS( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  680. COS( PI()/2 - rad2deg(90 - $pointY['lat'])) *
  681. COS( rad2deg($pointX['lng']) - rad2deg($pointY['lng'])) +
  682. SIN( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  683. SIN( PI()/2 - rad2deg(90 - $pointY['lat'])));
  684. $res = 6371.04 * acos(sin($pointY['lat'])*sin($pointX['lat'])+cos($pointY['lat'])*cos($pointX['lat'])*cos($pointY['lng'] - $pointX['lng']));
  685. */
  686. // seems to be the only working one (although slightly incorrect...)
  687. $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']))));
  688. return $res;
  689. }
  690. /**
  691. * Convert between units
  692. *
  693. * @param float $value
  694. * @param string $fromUnit (using class constants)
  695. * @param string $toUnit (using class constants)
  696. * @return float convertedValue
  697. * @throws CakeException
  698. */
  699. public function convert($value, $fromUnit, $toUnit) {
  700. if (!isset($this->units[($fromUnit = strtoupper($fromUnit))]) || !isset($this->units[($toUnit = strtoupper($toUnit))])) {
  701. throw new CakeException('Invalid Unit');
  702. }
  703. if ($fromUnit === 'M') {
  704. $value *= $this->units[$toUnit];
  705. } elseif ($toUnit === 'M') {
  706. $value /= $this->units[$fromUnit];
  707. } else {
  708. $value /= $this->units[$fromUnit];
  709. $value *= $this->units[$toUnit];
  710. }
  711. return $value;
  712. }
  713. /**
  714. * Fuzziness filter for coordinates (lat or lng).
  715. * Useful if you store other users' locations and want to grant some
  716. * privacy protection. This way the coordinates will be slightly modified.
  717. *
  718. * @param float coord Coordinates
  719. * @param int level The Level of blurness (0 = nothing to 5 = extrem)
  720. * - 1:
  721. * - 2:
  722. * - 3:
  723. * - 4:
  724. * - 5:
  725. * @return float Coordinates
  726. * @throws CakeException
  727. */
  728. public static function blur($coord, $level = 0) {
  729. if (!$level) {
  730. return $coord;
  731. }
  732. //TODO:
  733. switch ($level) {
  734. case 1:
  735. break;
  736. case 2:
  737. break;
  738. case 3:
  739. break;
  740. case 4:
  741. break;
  742. case 5:
  743. break;
  744. default:
  745. throw new CakeException(sprintf('Invalid level \'%s\'', $level));
  746. }
  747. $scrambleVal = 0.000001 * mt_rand(1000, 2000) * (mt_rand(0, 1) === 0 ? 1 : -1);
  748. return ($coord + $scrambleVal);
  749. //$scrambleVal *= (mt_rand(0,1) === 0 ? 1 : 2);
  750. //$scrambleVal *= (float)(2^$level);
  751. // TODO: + - by chance!!!
  752. return $coord + $scrambleVal;
  753. }
  754. const TYPE_ROOFTOP = 'ROOFTOP';
  755. const TYPE_RANGE_INTERPOLATED = 'RANGE_INTERPOLATED';
  756. const TYPE_GEOMETRIC_CENTER = 'GEOMETRIC_CENTER';
  757. const TYPE_APPROXIMATE = 'APPROXIMATE';
  758. /**
  759. * Return human error message string for response code of Geocoder API.
  760. *
  761. * @param mixed $code
  762. * @return string
  763. */
  764. public function statusMessage($code) {
  765. if (isset($this->statusCodes[$code])) {
  766. return __d('tools', $this->statusCodes[$code]);
  767. }
  768. return '';
  769. }
  770. const STATUS_SUCCESS = 'OK'; //200;
  771. const STATUS_TOO_MANY_QUERIES = 'OVER_QUERY_LIMIT'; //620;
  772. const STATUS_BAD_REQUEST = 'REQUEST_DENIED'; //400;
  773. const STATUS_MISSING_QUERY = 'INVALID_REQUEST';//601;
  774. const STATUS_UNKNOWN_ADDRESS = 'ZERO_RESULTS'; //602;
  775. /**
  776. * Return human error message string for error code of HttpSocket response.
  777. *
  778. * @param mixed $code
  779. * @return string
  780. */
  781. public function errorMessage($code) {
  782. $codes = array(
  783. static::CODE_SUCCESS => 'Success',
  784. static::CODE_BAD_REQUEST => 'Bad Request',
  785. static::CODE_MISSING_ADDRESS => 'Bad Address',
  786. static::CODE_UNKNOWN_ADDRESS => 'Unknown Address',
  787. static::CODE_UNAVAILABLE_ADDRESS => 'Unavailable Address',
  788. static::CODE_BAD_KEY => 'Bad Key',
  789. static::CODE_TOO_MANY_QUERIES => 'Too Many Queries',
  790. );
  791. if (isset($codes[$code])) {
  792. return __d('tools', $codes[$code]);
  793. }
  794. return '';
  795. }
  796. const CODE_SUCCESS = 200;
  797. const CODE_BAD_REQUEST = 400;
  798. const CODE_SERVER_ERROR = 500;
  799. const CODE_MISSING_ADDRESS = 601;
  800. const CODE_UNKNOWN_ADDRESS = 602;
  801. const CODE_UNAVAILABLE_ADDRESS = 603;
  802. const CODE_UNKNOWN_DIRECTIONS = 604;
  803. const CODE_BAD_KEY = 610;
  804. const CODE_TOO_MANY_QUERIES = 620;
  805. }
  806. /*
  807. TODO:
  808. http://code.google.com/intl/de-DE/apis/maps/documentation/geocoding/
  809. - whats the difference to "http://maps.google.com/maps/api/geocode/output?parameters"
  810. */