GeocodeLib.php 24 KB

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