GeocodeLib.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. <?php
  2. App::uses('String', 'Utility');
  3. App::uses('HttpSocketLib', 'Tools.Lib');
  4. /**
  5. * Geocode via google (UPDATE: api3)
  6. * @see DEPRECATED api2: http://code.google.com/intl/de-DE/apis/maps/articles/phpsqlgeocode.html
  7. * @see http://code.google.com/intl/de/apis/maps/documentation/geocoding/#Types
  8. *
  9. * Used by Tools.GeocoderBehavior
  10. *
  11. * TODOS (since 1.2):
  12. * - Work with exceptions in 2.x
  13. * - Rewrite in a cleaner 2.x way
  14. *
  15. * @author Mark Scherer
  16. * @cakephp 2.x
  17. * @licence MIT
  18. */
  19. class GeocodeLib {
  20. const BASE_URL = 'https://{host}/maps/api/geocode/{output}?';
  21. const DEFAULT_HOST = 'maps.googleapis.com';
  22. const ACC_COUNTRY = 0;
  23. const ACC_AAL1 = 1;
  24. const ACC_AAL2 = 2;
  25. const ACC_AAL3 = 3;
  26. const ACC_POSTAL = 4;
  27. const ACC_LOC = 5;
  28. const ACC_SUBLOC = 6;
  29. const ACC_ROUTE = 7;
  30. const ACC_INTERSEC = 8;
  31. const ACC_STREET = 9;
  32. const UNIT_KM = 'K';
  33. const UNIT_NAUTICAL = 'N';
  34. const UNIT_FEET = 'F';
  35. const UNIT_INCHES = 'I';
  36. const UNIT_MILES = 'M';
  37. // First tries with curl, then cake, then php
  38. public $use = array(
  39. 'curl' => true,
  40. 'cake' => true,
  41. 'php' => true
  42. );
  43. public $units = array(
  44. self::UNIT_KM => 1.609344,
  45. self::UNIT_NAUTICAL => 0.868976242,
  46. self::UNIT_FEET => 5280,
  47. self::UNIT_INCHES => 63360,
  48. self::UNIT_MILES => 1
  49. );
  50. /**
  51. * Validation and retrieval options
  52. * - use:
  53. * - log: false logs only real errors, true all activities
  54. * - pause: timeout to prevent blocking
  55. * - ...
  56. *
  57. */
  58. public $options = array(
  59. 'log' => false,
  60. 'pause' => 10000, # in ms
  61. 'min_accuracy' => self::ACC_COUNTRY,
  62. 'allow_inconclusive' => true,
  63. 'expect' => array(), # see accuracyTypes for details
  64. 'host' => null, # results in maps.google.com - use if you wish to obtain the closest address
  65. );
  66. /**
  67. * Url params
  68. */
  69. public $params = array(
  70. 'address' => '', # either address or latlng required!
  71. 'latlng' => '', # The textual latitude/longitude value for which you wish to obtain the closest, human-readable address
  72. 'region' => '', # The region code, specified as a ccTLD ("top-level domain") two-character
  73. 'language' => 'de',
  74. 'bounds' => '',
  75. 'sensor' => 'false', # device with gps module sensor
  76. //'key' => '' # not necessary anymore
  77. );
  78. protected $error = array();
  79. protected $debug = array();
  80. protected $result = null;
  81. public $statusCodes = array(
  82. self::CODE_SUCCESS => 'Success',
  83. self::CODE_BAD_REQUEST => 'Sensor param missing',
  84. self::CODE_MISSING_QUERY => 'Adress/LatLng missing',
  85. self::CODE_UNKNOWN_ADDRESS => 'Success, but to address found',
  86. self::CODE_TOO_MANY_QUERIES => 'Limit exceeded',
  87. );
  88. public $accuracyTypes = array(
  89. self::ACC_COUNTRY => 'country',
  90. self::ACC_AAL1 => 'administrative_area_level_1', # provinces/states
  91. self::ACC_AAL2 => 'administrative_area_level_2 ',
  92. self::ACC_AAL3 => 'administrative_area_level_3',
  93. self::ACC_LOC => 'locality',
  94. self::ACC_POSTAL => 'postal_code',
  95. self::ACC_SUBLOC => 'sublocality',
  96. self::ACC_ROUTE => 'route',
  97. self::ACC_INTERSEC => 'intersection',
  98. self::ACC_STREET => 'street_address',
  99. );
  100. public function __construct($options = array()) {
  101. $this->defaultParams = $this->params;
  102. $this->defaultOptions = $this->options;
  103. if (Configure::read('debug') > 0) {
  104. $this->options['log'] = true;
  105. }
  106. $this->setOptions($options);
  107. if (empty($this->options['host'])) {
  108. $this->options['host'] = self::DEFAULT_HOST;
  109. }
  110. }
  111. /**
  112. * @param array $params
  113. * @return void
  114. */
  115. public function setParams($params) {
  116. foreach ($params as $key => $value) {
  117. if ($key === 'sensor' && $value !== 'false' && $value !== 'true') {
  118. $value = !empty($value) ? 'true' : 'false';
  119. }
  120. $this->params[$key] = urlencode((string)$value);
  121. }
  122. }
  123. /**
  124. * @param array $options
  125. * @return void
  126. */
  127. public function setOptions($options) {
  128. foreach ($options as $key => $value) {
  129. $this->options[$key] = $value;
  130. }
  131. }
  132. public function setError($error) {
  133. if (empty($error)) {
  134. return;
  135. }
  136. $this->_setDebug('setError', $error);
  137. $this->error[] = $error;
  138. }
  139. public function error($asString = true, $separator = ', ') {
  140. if (!$asString) {
  141. return $this->error;
  142. }
  143. return implode(', ', $this->error);
  144. }
  145. /**
  146. * Reset - ready for the next request
  147. *
  148. * @param mixed boolean $full or string === 'params' to reset just params
  149. * @return void
  150. */
  151. public function reset($full = true) {
  152. $this->error = array();
  153. $this->result = null;
  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. public function url() {
  170. $params = array(
  171. 'host' => $this->options['host'],
  172. 'output' => 'json'
  173. );
  174. $url = String::insert(self::BASE_URL, $params, array('before' => '{', 'after' => '}', 'clean' => true));
  175. $params = array();
  176. foreach ($this->params as $key => $value) {
  177. if (!empty($value)) {
  178. $params[] = $key . '=' . $value;
  179. }
  180. }
  181. return $url . implode('&', $params);
  182. }
  183. /**
  184. * Seems like there are no inconclusive results anymore...
  185. *
  186. * @return boolean isInconclusive (or null if no query has been run yet)
  187. */
  188. public function isInconclusive() {
  189. if ($this->result === null) {
  190. return null;
  191. }
  192. return !empty($this->result['valid_results']) && $this->result['valid_results'] > 1;
  193. }
  194. /**
  195. * Return the geocoder result or empty array on failure
  196. *
  197. * @return array result
  198. */
  199. public function getResult() {
  200. if ($this->result === null) {
  201. return array();
  202. }
  203. return $this->result;
  204. }
  205. /**
  206. * Results usually from most accurate to least accurate result (street_address, ..., country)
  207. *
  208. * @param float $lat
  209. * @param float $lng
  210. * @param array $params
  211. * @return boolean Success
  212. */
  213. public function reverseGeocode($lat, $lng, $params = array()) {
  214. $this->reset(false);
  215. $this->_setDebug('reverseGeocode', compact('lat', 'lng', 'params'));
  216. $latlng = $lat . ',' . $lng;
  217. $this->setParams(array_merge($params, array('latlng' => $latlng)));
  218. $count = 0;
  219. $requestUrl = $this->url();
  220. while (true) {
  221. $result = $this->_fetch($requestUrl);
  222. if ($result === false || $result === null) {
  223. $this->setError('Could not retrieve url');
  224. CakeLog::write('geocode', __('Could not retrieve url with \'%s\'', $latlng));
  225. return false;
  226. }
  227. $this->_setDebug('raw', $result);
  228. $result = $this->_transform($result);
  229. if (!is_array($result)) {
  230. $this->setError('Result parsing failed');
  231. CakeLog::write('geocode', __('Failed reverseGeocode parsing of \'%s\'', $latlng));
  232. return false;
  233. }
  234. $status = $result['status'];
  235. if ($status == self::CODE_SUCCESS) {
  236. if (!$this->_process($result)) {
  237. return false;
  238. }
  239. // save Result
  240. if ($this->options['log']) {
  241. CakeLog::write('geocode', __('Address \'%s\' has been geocoded', $latlng));
  242. }
  243. break;
  244. } elseif ($status == self::CODE_TOO_MANY_QUERIES) {
  245. // sent geocodes too fast, delay +0.1 seconds
  246. if ($this->options['log']) {
  247. CakeLog::write('geocode', __('Delay necessary for \'%s\'', $latlng));
  248. }
  249. $count++;
  250. } else {
  251. // something went wrong
  252. $this->setError('Error ' . $status . (isset($this->statusCodes[$status]) ? ' (' . $this->statusCodes[$status] . ')' : ''));
  253. if ($this->options['log']) {
  254. CakeLog::write('geocode', __('Could not geocode \'%s\'', $latlng));
  255. }
  256. return false; # for now...
  257. }
  258. if ($count > 5) {
  259. if ($this->options['log']) {
  260. CakeLog::write('geocode', __('Aborted after too many trials with \'%s\'', $latlng));
  261. }
  262. $this->setError(__('Too many trials - abort'));
  263. return false;
  264. }
  265. $this->pause(true);
  266. }
  267. return true;
  268. }
  269. /**
  270. * Trying to avoid "TOO_MANY_QUERIES" error
  271. * @param boolean $raise If the pause length should be raised
  272. */
  273. public function pause($raise = false) {
  274. usleep($this->options['pause']);
  275. if ($raise) {
  276. $this->options['pause'] += 10000;
  277. }
  278. }
  279. /**
  280. * Actual querying.
  281. * The query will be flatted, and if multiple results are fetched, they will be found
  282. * in $result['all'].
  283. *
  284. * @param string $address
  285. * @param array $params
  286. * @return boolean Success
  287. */
  288. public function geocode($address, $params = array()) {
  289. $this->reset(false);
  290. $this->_setDebug('geocode', compact('address', 'params'));
  291. $this->setParams(array_merge($params, array('address' => $address)));
  292. $count = 0;
  293. $requestUrl = $this->url();
  294. while (true) {
  295. $result = $this->_fetch($requestUrl);
  296. if ($result === false || $result === null) {
  297. $this->setError('Could not retrieve url');
  298. CakeLog::write('geocode', 'Geocoder could not retrieve url with \'' . $address . '\'');
  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 geocode parsing of \'%s\'', $address));
  306. return false;
  307. }
  308. $status = $result['status'];
  309. if ($status == self::CODE_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', $address));
  316. }
  317. break;
  318. } elseif ($status == self::CODE_TOO_MANY_QUERIES) {
  319. // sent geocodes too fast, delay +0.1 seconds
  320. if ($this->options['log']) {
  321. CakeLog::write('geocode', __('Delay necessary for address \'%s\'', $address));
  322. }
  323. $count++;
  324. } else {
  325. // something went wrong
  326. $errorMessage = (isset($result['error_message']) ? $result['error_message'] : '');
  327. if (empty($errorMessage)) {
  328. $errorMessage = (isset($this->statusCodes[$status]) ? $this->statusCodes[$status] : '');
  329. }
  330. if (empty($errorMessage)) {
  331. $errorMessage = 'unknown';
  332. }
  333. $this->setError('Error ' . $status . ' (' . $errorMessage . ')');
  334. if ($this->options['log']) {
  335. CakeLog::write('geocode', __('Could not geocode \'%s\'', $address));
  336. }
  337. return false; # for now...
  338. }
  339. if ($count > 5) {
  340. if ($this->options['log']) {
  341. CakeLog::write('geocode', __('Aborted after too many trials with \'%s\'', $address));
  342. }
  343. $this->setError('Too many trials - abort');
  344. return false;
  345. }
  346. $this->pause(true);
  347. }
  348. return true;
  349. }
  350. /**
  351. * GeocodeLib::_process()
  352. *
  353. * @param mixed $result
  354. * @return boolean Success
  355. */
  356. protected function _process($result) {
  357. $this->result = null;
  358. $validResults = 0;
  359. foreach ($result['results'] as $res) {
  360. if (!$res['valid_type']) {
  361. continue;
  362. }
  363. $validResults++;
  364. if (isset($this->result)) {
  365. continue;
  366. }
  367. $this->result = $res;
  368. }
  369. $this->result['valid_results'] = $validResults;
  370. $this->result['all'] = $result['results'];
  371. // validate
  372. if (!$this->options['allow_inconclusive'] && $validResults > 1) {
  373. $this->setError(__('Inconclusive result (total of %s)', $validResults));
  374. return false;
  375. }
  376. if ($this->_isNotAccurateEnough($this->result['accuracy'])) {
  377. $minAccuracy = $this->accuracyTypes[$this->options['min_accuracy']];
  378. $this->setError(__('Accuracy not good enough (%s instead of at least %s)', $this->result['accuracy_name'], $minAccuracy));
  379. return false;
  380. }
  381. if (!empty($this->options['expect'])) {
  382. $expected = (array)$this->options['expect'];
  383. foreach ($expected as $k => $v) {
  384. $accuracy = is_int($v) ? $this->accuracyTypes[$v] : $v;
  385. $expected[$k] = $accuracy;
  386. }
  387. $found = array_intersect($this->result['types'], $expected);
  388. $validExpectation = !empty($found);
  389. if (!$validExpectation) {
  390. $this->setError(__('Expectation not reached (we have %s instead of at least one of %s)',
  391. implode(', ', $found),
  392. implode(', ', $expected)
  393. ));
  394. return false;
  395. }
  396. }
  397. return true;
  398. }
  399. /**
  400. * GeocodeLib::accuracyTypes()
  401. *
  402. * @param mixed $value
  403. * @return mixed Type or types
  404. */
  405. public function accuracyTypes($value = null) {
  406. if ($value !== null) {
  407. if (isset($this->accuracyTypes[$value])) {
  408. return $this->accuracyTypes[$value];
  409. }
  410. return null;
  411. }
  412. return $this->accuracyTypes;
  413. }
  414. protected function _validate($result) {
  415. $validType = false;
  416. foreach ($result['types'] as $type) {
  417. if (in_array($type, $this->accuracyTypes, true)) {
  418. $validType = true;
  419. break;
  420. }
  421. }
  422. $result['valid_type'] = $validType;
  423. return $result;
  424. }
  425. protected function _accuracy($result) {
  426. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  427. $accuracy = 0;
  428. foreach ($accuracyTypes as $key => $field) {
  429. if (array_key_exists($field, $result) && !empty($result[$field])) {
  430. $accuracy = $key;
  431. break;
  432. }
  433. }
  434. $result['accuracy'] = $accuracy;
  435. $result['accuracy_name'] = $this->accuracyTypes[$accuracy];
  436. return $result;
  437. }
  438. /**
  439. * @param int $accuracy
  440. * @return boolean $notAccurateEnough
  441. */
  442. protected function _isNotAccurateEnough($accuracy) {
  443. if (!array_key_exists($accuracy, $this->accuracyTypes)) {
  444. $accuracy = 0;
  445. }
  446. // is our current accuracy < minimum?
  447. return $accuracy < $this->options['min_accuracy'];
  448. }
  449. /**
  450. * GeocodeLib::_transform()
  451. *
  452. * @param string|array $record JSON string or array
  453. * @return array
  454. */
  455. protected function _transform($record) {
  456. if (!is_array($record)) {
  457. $record = json_decode($record, true);
  458. }
  459. $record['results'] = $this->_transformData($record['results']);
  460. return $record;
  461. }
  462. /**
  463. * Try to find the max accuracy level
  464. * - look through all fields and
  465. * attempt to find the first record which matches an accuracyTypes field
  466. *
  467. * @param array $record
  468. * @return int|null $maxAccuracy 9-0 as defined in $this->accuracyTypes
  469. */
  470. protected function _getMaxAccuracy($record) {
  471. if (!is_array($record)) {
  472. return null;
  473. }
  474. $accuracyTypes = array_reverse($this->accuracyTypes, true);
  475. foreach ($accuracyTypes as $key => $field) {
  476. if (array_key_exists($field, $record) && !empty($record[$field])) {
  477. // found $field -- return it's $key
  478. return $key;
  479. }
  480. }
  481. // not found? recurse into all possible children
  482. foreach (array_keys($record) as $key) {
  483. if (empty($record[$key]) || !is_array($record[$key])) {
  484. continue;
  485. }
  486. $accuracy = $this->_getMaxAccuracy($record[$key]);
  487. if ($accuracy !== null) {
  488. // found in nested value
  489. return $accuracy;
  490. }
  491. }
  492. return null;
  493. }
  494. /**
  495. * Flattens result array and returns clean record
  496. * keys:
  497. * - formatted_address, type, country, country_code, country_province, country_province_code, locality, sublocality, postal_code, route, lat, lng, location_type, viewport, bounds
  498. *
  499. * @param mixed $record any level of input, whole raw array or records or single record
  500. * @return array $record organized & normalized
  501. */
  502. protected function _transformData($record) {
  503. if (!array_key_exists('address_components', $record)) {
  504. foreach (array_keys($record) as $key) {
  505. $record[$key] = $this->_transformData($record[$key]);
  506. }
  507. return $record;
  508. }
  509. $res = array();
  510. // handle and organize address_components
  511. $components = array();
  512. foreach ($record['address_components'] as $c) {
  513. $types = array();
  514. $type = $c['types'][0];
  515. $types = $c['types'];
  516. if (array_key_exists($type, $components)) {
  517. $components[$type]['name'] .= ' ' . $c['long_name'];
  518. $components[$type]['abbr'] .= ' ' . $c['short_name'];
  519. $components[$type]['types'] += $types;
  520. } else {
  521. $components[$type] = array('name' => $c['long_name'], 'abbr' => $c['short_name'], 'types' => $types);
  522. }
  523. }
  524. $res['formatted_address'] = $record['formatted_address'];
  525. if (array_key_exists('country', $components)) {
  526. $res['country'] = $components['country']['name'];
  527. $res['country_code'] = $components['country']['abbr'];
  528. } else {
  529. $res['country'] = $res['country_code'] = '';
  530. }
  531. if (array_key_exists('administrative_area_level_1', $components)) {
  532. $res['country_province'] = $components['administrative_area_level_1']['name'];
  533. $res['country_province_code'] = $components['administrative_area_level_1']['abbr'];
  534. } else {
  535. $res['country_province'] = $res['country_province_code'] = '';
  536. }
  537. if (array_key_exists('postal_code', $components)) {
  538. $res['postal_code'] = $components['postal_code']['name'];
  539. } else {
  540. $res['postal_code'] = '';
  541. }
  542. if (array_key_exists('locality', $components)) {
  543. $res['locality'] = $components['locality']['name'];
  544. } else {
  545. $res['locality'] = '';
  546. }
  547. if (array_key_exists('sublocality', $components)) {
  548. $res['sublocality'] = $components['sublocality']['name'];
  549. } else {
  550. $res['sublocality'] = '';
  551. }
  552. if (array_key_exists('route', $components)) {
  553. $res['route'] = $components['route']['name'];
  554. if (array_key_exists('street_number', $components)) {
  555. $res['route'] .= ' ' . $components['street_number']['name'];
  556. }
  557. } else {
  558. $res['route'] = '';
  559. }
  560. // determine accuracy types
  561. if (array_key_exists('types', $record)) {
  562. $res['types'] = $record['types'];
  563. } else {
  564. $res['types'] = array();
  565. }
  566. //TODO: add more
  567. $res['lat'] = $record['geometry']['location']['lat'];
  568. $res['lng'] = $record['geometry']['location']['lng'];
  569. $res['location_type'] = $record['geometry']['location_type'];
  570. if (!empty($record['geometry']['viewport'])) {
  571. $res['viewport'] = array('sw' => $record['geometry']['viewport']['southwest'], 'ne' => $record['geometry']['viewport']['northeast']);
  572. }
  573. if (!empty($record['geometry']['bounds'])) {
  574. $res['bounds'] = array('sw' => $record['geometry']['bounds']['southwest'], 'ne' => $record['geometry']['bounds']['northeast']);
  575. }
  576. // manuell corrections
  577. $array = array(
  578. 'Berlin' => 'BE',
  579. );
  580. if (!empty($res['country_province_code']) && array_key_exists($res['country_province_code'], $array)) {
  581. $res['country_province_code'] = $array[$res['country_province_code']];
  582. }
  583. if (!empty($record['postcode_localities'])) {
  584. $res['postcode_localities'] = $record['postcode_localities'];
  585. }
  586. if (!empty($record['address_components'])) {
  587. $res['address_components'] = $record['address_components'];
  588. }
  589. $res = $this->_validate($res);
  590. $res = $this->_accuracy($res);
  591. //debug($res);die();
  592. return $res;
  593. }
  594. /**
  595. * Fetches url with curl if available
  596. * fallbacks: cake and php
  597. * note: expects url with json encoded content
  598. *
  599. * @return mixed
  600. **/
  601. protected function _fetch($url) {
  602. $this->HttpSocket = new HttpSocketLib($this->use);
  603. if ($res = $this->HttpSocket->fetch($url, 'CakePHP Geocode Lib')) {
  604. return $res;
  605. }
  606. $this->setError($this->HttpSocket->error());
  607. return false;
  608. }
  609. /**
  610. * return debugging info
  611. *
  612. * @return array $debug
  613. */
  614. public function debug() {
  615. $this->debug['result'] = $this->result;
  616. return $this->debug;
  617. }
  618. /**
  619. * set debugging info
  620. *
  621. * @param string $key
  622. * @param mixed $data
  623. * @return void
  624. */
  625. public function _setDebug($key, $data = null) {
  626. $this->debug[$key] = $data;
  627. }
  628. /**
  629. * Calculates Distance between two points - each: array('lat'=>x,'lng'=>y)
  630. * DB:
  631. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  632. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  633. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  634. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  635. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  636. 'AS distance'
  637. *
  638. * @param array pointX
  639. * @param array pointY
  640. * @param float $unit (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet)
  641. * @return int Distance in km
  642. */
  643. public function distance(array $pointX, array $pointY, $unit = null) {
  644. if (empty($unit) || !array_key_exists(($unit = strtoupper($unit)), $this->units)) {
  645. $unit = array_keys($this->units);
  646. $unit = $unit[0];
  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 char $fromUnit (using class constants)
  679. * @param char $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 integer 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. const CODE_SUCCESS = 'OK'; //200;
  743. const CODE_TOO_MANY_QUERIES = 'OVER_QUERY_LIMIT'; //620;
  744. const CODE_BAD_REQUEST = 'REQUEST_DENIED'; //400;
  745. const CODE_MISSING_QUERY = 'INVALID_REQUEST';//601;
  746. const CODE_UNKNOWN_ADDRESS = 'ZERO_RESULTS'; //602;
  747. /*
  748. const CODE_SERVER_ERROR = 500;
  749. const CODE_UNAVAILABLE_ADDRESS = 603;
  750. const CODE_UNKNOWN_DIRECTIONS = 604;
  751. const CODE_BAD_KEY = 610;
  752. */
  753. }
  754. /*
  755. TODO:
  756. http://code.google.com/intl/de-DE/apis/maps/documentation/geocoding/
  757. - whats the difference to "http://maps.google.com/maps/api/geocode/output?parameters"
  758. */