GeocodeLib.php 24 KB

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