GeocodeLib.php 28 KB

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