GeocodeLib.php 25 KB

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