GeocodeLib.php 24 KB

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