GeocodeLib.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. $params = array('address' => $address) + $params;
  219. $this->setParams($params);
  220. $count = 0;
  221. $requestUrl = $this->_url();
  222. while (true) {
  223. $result = $this->_fetch($requestUrl, $this->params);
  224. if ($result === false || $result === null) {
  225. $this->setError('Could not retrieve url');
  226. CakeLog::write('geocode', 'Geocoder could not retrieve url with \'' . $address . '\'');
  227. return false;
  228. }
  229. $this->_setDebug('raw', $result);
  230. $result = $this->_transform($result);
  231. if (!is_array($result)) {
  232. $this->setError('Result parsing failed');
  233. CakeLog::write('geocode', __('Failed geocode parsing of \'%s\'', $address));
  234. return false;
  235. }
  236. $status = $result['status'];
  237. if ($status == self::STATUS_SUCCESS) {
  238. if (!$this->_process($result)) {
  239. return false;
  240. }
  241. // save Result
  242. if ($this->options['log']) {
  243. CakeLog::write('geocode', __('Address \'%s\' has been geocoded', $address));
  244. }
  245. break;
  246. } elseif ($status == self::STATUS_TOO_MANY_QUERIES) {
  247. // sent geocodes too fast, delay +0.1 seconds
  248. if ($this->options['log']) {
  249. CakeLog::write('geocode', __('Delay necessary for address \'%s\'', $address));
  250. }
  251. $count++;
  252. } else {
  253. // something went wrong
  254. $errorMessage = (isset($result['error_message']) ? $result['error_message'] : '');
  255. if (empty($errorMessage)) {
  256. $errorMessage = $this->errorMessage($status);
  257. }
  258. if (empty($errorMessage)) {
  259. $errorMessage = 'unknown';
  260. }
  261. $this->setError('Error ' . $status . ' (' . $errorMessage . ')');
  262. if ($this->options['log']) {
  263. CakeLog::write('geocode', __('Could not geocode \'%s\'', $address));
  264. }
  265. return false; # for now...
  266. }
  267. if ($count > 5) {
  268. if ($this->options['log']) {
  269. CakeLog::write('geocode', __('Aborted after too many trials with \'%s\'', $address));
  270. }
  271. $this->setError('Too many trials - abort');
  272. return false;
  273. }
  274. $this->pause(true);
  275. }
  276. return true;
  277. }
  278. /**
  279. * Results usually from most accurate to least accurate result (street_address, ..., country)
  280. *
  281. * @param float $lat
  282. * @param float $lng
  283. * @param array $params
  284. * @return bool Success
  285. */
  286. public function reverseGeocode($lat, $lng, $params = array()) {
  287. $this->reset(false);
  288. $this->_setDebug('reverseGeocode', compact('lat', 'lng', 'params'));
  289. $latlng = $lat . ',' . $lng;
  290. $params = array('latlng' => $latlng) + $params;
  291. $this->setParams($params);
  292. $count = 0;
  293. $requestUrl = $this->_url();
  294. while (true) {
  295. $result = $this->_fetch($requestUrl, $this->params);
  296. if ($result === false || $result === null) {
  297. $this->setError('Could not retrieve url');
  298. CakeLog::write('geocode', __('Could not retrieve url with \'%s\'', $latlng));
  299. return false;
  300. }
  301. $this->_setDebug('raw', $result);
  302. $result = $this->_transform($result);
  303. if (!is_array($result)) {
  304. $this->setError('Result parsing failed');
  305. CakeLog::write('geocode', __('Failed reverseGeocode parsing of \'%s\'', $latlng));
  306. return false;
  307. }
  308. $status = $result['status'];
  309. if ($status == self::STATUS_SUCCESS) {
  310. if (!$this->_process($result)) {
  311. return false;
  312. }
  313. // save Result
  314. if ($this->options['log']) {
  315. CakeLog::write('geocode', __('Address \'%s\' has been geocoded', $latlng));
  316. }
  317. break;
  318. } elseif ($status == self::STATUS_TOO_MANY_QUERIES) {
  319. // sent geocodes too fast, delay +0.1 seconds
  320. if ($this->options['log']) {
  321. CakeLog::write('geocode', __('Delay necessary for \'%s\'', $latlng));
  322. }
  323. $count++;
  324. } else {
  325. // something went wrong
  326. $this->setError('Error ' . $status . (isset($this->statusCodes[$status]) ? ' (' . $this->statusCodes[$status] . ')' : ''));
  327. if ($this->options['log']) {
  328. CakeLog::write('geocode', __('Could not geocode \'%s\'', $latlng));
  329. }
  330. return false; # for now...
  331. }
  332. if ($count > 5) {
  333. if ($this->options['log']) {
  334. CakeLog::write('geocode', __('Aborted after too many trials with \'%s\'', $latlng));
  335. }
  336. $this->setError(__('Too many trials - abort'));
  337. return false;
  338. }
  339. $this->pause(true);
  340. }
  341. return true;
  342. }
  343. /**
  344. * GeocodeLib::_process()
  345. *
  346. * @param mixed $result
  347. * @return bool Success
  348. */
  349. protected function _process($result) {
  350. $this->result = null;
  351. $validResults = 0;
  352. foreach ($result['results'] as $res) {
  353. if (!$res['valid_type']) {
  354. continue;
  355. }
  356. $validResults++;
  357. if (isset($this->result)) {
  358. continue;
  359. }
  360. $this->result = $res;
  361. }
  362. $this->result['valid_results'] = $validResults;
  363. $this->result['all'] = $result['results'];
  364. // validate
  365. if (!$this->options['allow_inconclusive'] && $validResults > 1) {
  366. $this->setError(__('Inconclusive result (total of %s)', $validResults));
  367. return false;
  368. }
  369. if ($this->_isNotAccurateEnough($this->result['accuracy'])) {
  370. $minAccuracy = $this->accuracyTypes[$this->options['min_accuracy']];
  371. $this->setError(__('Accuracy not good enough (%s instead of at least %s)', $this->result['accuracy_name'], $minAccuracy));
  372. return false;
  373. }
  374. if (!empty($this->options['expect'])) {
  375. $expected = (array)$this->options['expect'];
  376. foreach ($expected as $k => $v) {
  377. $accuracy = is_int($v) ? $this->accuracyTypes[$v] : $v;
  378. $expected[$k] = $accuracy;
  379. }
  380. $found = array_intersect($this->result['types'], $expected);
  381. $validExpectation = !empty($found);
  382. if (!$validExpectation) {
  383. $this->setError(__('Expectation not reached (we have %s instead of at least one of %s)',
  384. implode(', ', $found),
  385. implode(', ', $expected)
  386. ));
  387. return false;
  388. }
  389. }
  390. return true;
  391. }
  392. /**
  393. * GeocodeLib::accuracyTypes()
  394. *
  395. * @param mixed $value
  396. * @return mixed Type or types
  397. */
  398. public function accuracyTypes($value = null) {
  399. if ($value !== null) {
  400. if (isset($this->accuracyTypes[$value])) {
  401. return $this->accuracyTypes[$value];
  402. }
  403. return null;
  404. }
  405. return $this->accuracyTypes;
  406. }
  407. protected function _validate($result) {
  408. $validType = false;
  409. foreach ($result['types'] as $type) {
  410. if (in_array($type, $this->accuracyTypes, true)) {
  411. $validType = true;
  412. break;
  413. }
  414. }
  415. $result['valid_type'] = $validType;
  416. return $result;
  417. }
  418. protected function _accuracy($result) {
  419. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  420. $accuracy = 0;
  421. foreach ($accuracyTypes as $key => $field) {
  422. if (array_key_exists($field, $result) && !empty($result[$field])) {
  423. $accuracy = $key;
  424. break;
  425. }
  426. }
  427. $result['accuracy'] = $accuracy;
  428. $result['accuracy_name'] = $this->accuracyTypes[$accuracy];
  429. return $result;
  430. }
  431. /**
  432. * @param int $accuracy
  433. * @return bool notAccurateEnough
  434. */
  435. protected function _isNotAccurateEnough($accuracy) {
  436. if (!array_key_exists($accuracy, $this->accuracyTypes)) {
  437. $accuracy = 0;
  438. }
  439. // is our current accuracy < minimum?
  440. return $accuracy < $this->options['min_accuracy'];
  441. }
  442. /**
  443. * GeocodeLib::_transform()
  444. *
  445. * @param string|array $record JSON string or array
  446. * @return array
  447. */
  448. protected function _transform($record) {
  449. if (!is_array($record)) {
  450. $record = json_decode($record, true);
  451. }
  452. $record['results'] = $this->_transformData($record['results']);
  453. return $record;
  454. }
  455. /**
  456. * Try to find the max accuracy level
  457. * - look through all fields and
  458. * attempt to find the first record which matches an accuracyTypes field
  459. *
  460. * @param array $record
  461. * @return int|null $maxAccuracy 9-0 as defined in $this->accuracyTypes
  462. */
  463. protected function _getMaxAccuracy($record) {
  464. if (!is_array($record)) {
  465. return null;
  466. }
  467. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  468. foreach ($accuracyTypes as $key => $field) {
  469. if (array_key_exists($field, $record) && !empty($record[$field])) {
  470. // found $field -- return it's $key
  471. return $key;
  472. }
  473. }
  474. // not found? recurse into all possible children
  475. foreach (array_keys($record) as $key) {
  476. if (empty($record[$key]) || !is_array($record[$key])) {
  477. continue;
  478. }
  479. $accuracy = $this->_getMaxAccuracy($record[$key]);
  480. if ($accuracy !== null) {
  481. // found in nested value
  482. return $accuracy;
  483. }
  484. }
  485. return null;
  486. }
  487. /**
  488. * Flattens result array and returns clean record
  489. * keys:
  490. * - formatted_address, type, country, country_code, country_province, country_province_code, locality, sublocality, postal_code, route, lat, lng, location_type, viewport, bounds
  491. *
  492. * @param mixed $record any level of input, whole raw array or records or single record
  493. * @return array record organized & normalized
  494. */
  495. protected function _transformData($record) {
  496. if (!array_key_exists('address_components', $record)) {
  497. foreach (array_keys($record) as $key) {
  498. $record[$key] = $this->_transformData($record[$key]);
  499. }
  500. return $record;
  501. }
  502. $res = array();
  503. // handle and organize address_components
  504. $components = array();
  505. foreach ($record['address_components'] as $c) {
  506. $type = $c['types'][0];
  507. $types = $c['types'];
  508. if (array_key_exists($type, $components)) {
  509. $components[$type]['name'] .= ' ' . $c['long_name'];
  510. $components[$type]['abbr'] .= ' ' . $c['short_name'];
  511. $components[$type]['types'] += $types;
  512. } else {
  513. $components[$type] = array('name' => $c['long_name'], 'abbr' => $c['short_name'], 'types' => $types);
  514. }
  515. }
  516. $res['formatted_address'] = $record['formatted_address'];
  517. if (array_key_exists('country', $components)) {
  518. $res['country'] = $components['country']['name'];
  519. $res['country_code'] = $components['country']['abbr'];
  520. } else {
  521. $res['country'] = $res['country_code'] = '';
  522. }
  523. if (array_key_exists('administrative_area_level_1', $components)) {
  524. $res['country_province'] = $components['administrative_area_level_1']['name'];
  525. $res['country_province_code'] = $components['administrative_area_level_1']['abbr'];
  526. } else {
  527. $res['country_province'] = $res['country_province_code'] = '';
  528. }
  529. if (array_key_exists('postal_code', $components)) {
  530. $res['postal_code'] = $components['postal_code']['name'];
  531. } else {
  532. $res['postal_code'] = '';
  533. }
  534. if (array_key_exists('locality', $components)) {
  535. $res['locality'] = $components['locality']['name'];
  536. } else {
  537. $res['locality'] = '';
  538. }
  539. if (array_key_exists('sublocality', $components)) {
  540. $res['sublocality'] = $components['sublocality']['name'];
  541. } else {
  542. $res['sublocality'] = '';
  543. }
  544. if (array_key_exists('route', $components)) {
  545. $res['route'] = $components['route']['name'];
  546. if (array_key_exists('street_number', $components)) {
  547. $res['route'] .= ' ' . $components['street_number']['name'];
  548. }
  549. } else {
  550. $res['route'] = '';
  551. }
  552. // determine accuracy types
  553. if (array_key_exists('types', $record)) {
  554. $res['types'] = $record['types'];
  555. } else {
  556. $res['types'] = array();
  557. }
  558. //TODO: add more
  559. $res['lat'] = $record['geometry']['location']['lat'];
  560. $res['lng'] = $record['geometry']['location']['lng'];
  561. $res['location_type'] = $record['geometry']['location_type'];
  562. if (!empty($record['geometry']['viewport'])) {
  563. $res['viewport'] = array('sw' => $record['geometry']['viewport']['southwest'], 'ne' => $record['geometry']['viewport']['northeast']);
  564. }
  565. if (!empty($record['geometry']['bounds'])) {
  566. $res['bounds'] = array('sw' => $record['geometry']['bounds']['southwest'], 'ne' => $record['geometry']['bounds']['northeast']);
  567. }
  568. // manuell corrections
  569. $array = array(
  570. 'Berlin' => 'BE',
  571. );
  572. if (!empty($res['country_province_code']) && array_key_exists($res['country_province_code'], $array)) {
  573. $res['country_province_code'] = $array[$res['country_province_code']];
  574. }
  575. if (!empty($record['postcode_localities'])) {
  576. $res['postcode_localities'] = $record['postcode_localities'];
  577. }
  578. if (!empty($record['address_components'])) {
  579. $res['address_components'] = $record['address_components'];
  580. }
  581. $res = $this->_validate($res);
  582. $res = $this->_accuracy($res);
  583. return $res;
  584. }
  585. /**
  586. * Fetches url with curl if available
  587. * fallbacks: cake and php
  588. * note: expects url with json encoded content
  589. *
  590. * @return mixed
  591. **/
  592. protected function _fetch($url, $query) {
  593. $this->HttpSocket = new HttpSocket();
  594. foreach ($query as $k => $v) {
  595. if ($v === '') {
  596. unset($query[$k]);
  597. }
  598. }
  599. if ($res = $this->HttpSocket->get($url, $query)) {
  600. return $res->body;
  601. }
  602. $errorCode = $this->HttpSocket->response->code;
  603. $this->setError('Error '. $errorCode. ': ' . $this->errorMessage($errorCode));
  604. return false;
  605. }
  606. /**
  607. * return debugging info
  608. *
  609. * @return array debug
  610. */
  611. public function debug() {
  612. $this->debug['result'] = $this->result;
  613. return $this->debug;
  614. }
  615. /**
  616. * set debugging info
  617. *
  618. * @param string $key
  619. * @param mixed $data
  620. * @return void
  621. */
  622. public function _setDebug($key, $data = null) {
  623. $this->debug[$key] = $data;
  624. }
  625. /**
  626. * Calculates Distance between two points - each: array('lat'=>x,'lng'=>y)
  627. * DB:
  628. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  629. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  630. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  631. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  632. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  633. 'AS distance'
  634. *
  635. * @param array pointX
  636. * @param array pointY
  637. * @param string $unit Unit char or constant (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet)
  638. * @return int Distance in km
  639. */
  640. public function distance(array $pointX, array $pointY, $unit = null) {
  641. if (empty($unit)) {
  642. $unit = array_keys($this->units);
  643. $unit = $unit[0];
  644. }
  645. $unit = strtoupper($unit);
  646. if (!isset($this->units[$unit])) {
  647. throw new CakeException(__('Invalid Unit: %s', $unit));
  648. }
  649. $res = $this->calculateDistance($pointX, $pointY);
  650. if (isset($this->units[$unit])) {
  651. $res *= $this->units[$unit];
  652. }
  653. return ceil($res);
  654. }
  655. /**
  656. * GeocodeLib::calculateDistance()
  657. *
  658. * @param array $pointX
  659. * @param array $pointY
  660. * @return float
  661. */
  662. public static function calculateDistance(array $pointX, array $pointY) {
  663. /*
  664. $res = 6371.04 * ACOS( COS( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  665. COS( PI()/2 - rad2deg(90 - $pointY['lat'])) *
  666. COS( rad2deg($pointX['lng']) - rad2deg($pointY['lng'])) +
  667. SIN( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  668. SIN( PI()/2 - rad2deg(90 - $pointY['lat'])));
  669. $res = 6371.04 * acos(sin($pointY['lat'])*sin($pointX['lat'])+cos($pointY['lat'])*cos($pointX['lat'])*cos($pointY['lng'] - $pointX['lng']));
  670. */
  671. // seems to be the only working one (although slightly incorrect...)
  672. $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']))));
  673. return $res;
  674. }
  675. /**
  676. * Convert between units
  677. *
  678. * @param float $value
  679. * @param string $fromUnit (using class constants)
  680. * @param string $toUnit (using class constants)
  681. * @return float convertedValue
  682. * @throws CakeException
  683. */
  684. public function convert($value, $fromUnit, $toUnit) {
  685. if (!isset($this->units[($fromUnit = strtoupper($fromUnit))]) || !isset($this->units[($toUnit = strtoupper($toUnit))])) {
  686. throw new CakeException(__('Invalid Unit'));
  687. }
  688. if ($fromUnit === 'M') {
  689. $value *= $this->units[$toUnit];
  690. } elseif ($toUnit === 'M') {
  691. $value /= $this->units[$fromUnit];
  692. } else {
  693. $value /= $this->units[$fromUnit];
  694. $value *= $this->units[$toUnit];
  695. }
  696. return $value;
  697. }
  698. /**
  699. * Fuzziness filter for coordinates (lat or lng).
  700. * Useful if you store other users' locations and want to grant some
  701. * privacy protection. This way the coordinates will be slightly modified.
  702. *
  703. * @param float coord Coordinates
  704. * @param int level The Level of blurness (0 = nothing to 5 = extrem)
  705. * - 1:
  706. * - 2:
  707. * - 3:
  708. * - 4:
  709. * - 5:
  710. * @return float Coordinates
  711. * @throws CakeException
  712. */
  713. public static function blur($coord, $level = 0) {
  714. if (!$level) {
  715. return $coord;
  716. }
  717. //TODO:
  718. switch ($level) {
  719. case 1:
  720. break;
  721. case 2:
  722. break;
  723. case 3:
  724. break;
  725. case 4:
  726. break;
  727. case 5:
  728. break;
  729. default:
  730. throw new CakeException(__('Invalid level \'%s\'', $level));
  731. }
  732. $scrambleVal = 0.000001 * mt_rand(1000, 2000) * (mt_rand(0, 1) === 0 ? 1 : -1);
  733. return ($coord + $scrambleVal);
  734. //$scrambleVal *= (mt_rand(0,1) === 0 ? 1 : 2);
  735. //$scrambleVal *= (float)(2^$level);
  736. // TODO: + - by chance!!!
  737. return $coord + $scrambleVal;
  738. }
  739. const TYPE_ROOFTOP = 'ROOFTOP';
  740. const TYPE_RANGE_INTERPOLATED = 'RANGE_INTERPOLATED';
  741. const TYPE_GEOMETRIC_CENTER = 'GEOMETRIC_CENTER';
  742. const TYPE_APPROXIMATE = 'APPROXIMATE';
  743. /**
  744. * Return human error message string for response code of Geocoder API.
  745. *
  746. * @param mixed $code
  747. * @return string
  748. */
  749. public function statusMessage($code) {
  750. if (isset($this->statusCodes[$code])) {
  751. return __($this->statusCodes[$code]);
  752. }
  753. return '';
  754. }
  755. const STATUS_SUCCESS = 'OK'; //200;
  756. const STATUS_TOO_MANY_QUERIES = 'OVER_QUERY_LIMIT'; //620;
  757. const STATUS_BAD_REQUEST = 'REQUEST_DENIED'; //400;
  758. const STATUS_MISSING_QUERY = 'INVALID_REQUEST';//601;
  759. const STATUS_UNKNOWN_ADDRESS = 'ZERO_RESULTS'; //602;
  760. /**
  761. * Return human error message string for error code of HttpSocket response.
  762. *
  763. * @param mixed $code
  764. * @return string
  765. */
  766. public function errorMessage($code) {
  767. $codes = array(
  768. self::CODE_SUCCESS => 'Success',
  769. self::CODE_BAD_REQUEST => 'Bad Request',
  770. self::CODE_MISSING_ADDRESS => 'Bad Address',
  771. self::CODE_UNKNOWN_ADDRESS => 'Unknown Address',
  772. self::CODE_UNAVAILABLE_ADDRESS => 'Unavailable Address',
  773. self::CODE_BAD_KEY => 'Bad Key',
  774. self::CODE_TOO_MANY_QUERIES => 'Too Many Queries',
  775. );
  776. if (isset($codes[$code])) {
  777. return __($codes[$code]);
  778. }
  779. return '';
  780. }
  781. const CODE_SUCCESS = 200;
  782. const CODE_BAD_REQUEST = 400;
  783. const CODE_SERVER_ERROR = 500;
  784. const CODE_MISSING_ADDRESS = 601;
  785. const CODE_UNKNOWN_ADDRESS = 602;
  786. const CODE_UNAVAILABLE_ADDRESS = 603;
  787. const CODE_UNKNOWN_DIRECTIONS = 604;
  788. const CODE_BAD_KEY = 610;
  789. const CODE_TOO_MANY_QUERIES = 620;
  790. }
  791. /*
  792. TODO:
  793. http://code.google.com/intl/de-DE/apis/maps/documentation/geocoding/
  794. - whats the difference to "http://maps.google.com/maps/api/geocode/output?parameters"
  795. */