GeocodeLib.php 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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 array result
  205. */
  206. public function getResult() {
  207. if ($this->result === null) {
  208. return false;
  209. }
  210. if (is_string($this->result)) {
  211. return $this->_transform($this->result);
  212. }
  213. if (!is_array($this->result)) {
  214. return false;
  215. }
  216. return $this->result;
  217. }
  218. /**
  219. * Results usually from most accurate to least accurate result (street_address, ..., country)
  220. *
  221. * @param float $lat
  222. * @param float $lng
  223. * @param array $params
  224. * - allow_inconclusive
  225. * - min_accuracy
  226. * @return boolean Success
  227. */
  228. public function reverseGeocode($lat, $lng, $params = array()) {
  229. $this->reset(false);
  230. $this->debugSet('reverseGeocode', compact('lat', 'lng', 'params'));
  231. $latlng = $lat . ',' . $lng;
  232. $this->setParams(array_merge($params, array('latlng' => $latlng)));
  233. $count = 0;
  234. $requestUrl = $this->url();
  235. while (true) {
  236. $result = $this->_fetch($requestUrl);
  237. if ($result === false || $result === null) {
  238. $this->setError('Could not retrieve url');
  239. CakeLog::write('geocode', __('Could not retrieve url with \'%s\'', $latlng));
  240. return false;
  241. }
  242. $this->debugSet('raw', $result);
  243. $result = $this->_transform($result);
  244. if (!is_array($result)) {
  245. $this->setError('Result parsing failed');
  246. CakeLog::write('geocode', __('Failed reverseGeocode parsing of \'%s\'', $latlng));
  247. return false;
  248. }
  249. $status = $result['status'];
  250. //debug(compact('result', 'requestUrl', 'success'));
  251. if ($status == self::CODE_SUCCESS) {
  252. // validate
  253. if (isset($result['results'][0]) && !$this->options['allow_inconclusive']) {
  254. $this->setError(__('Inconclusive result (total of %s)', count($result['results'])));
  255. $this->result = $result['results'];
  256. return false;
  257. }
  258. if (isset($result['results'][0])) {
  259. $result['result'] = $result['results'][0];
  260. }
  261. $accuracy = $this->_getMaxAccuracy($result['result']);
  262. if ($this->_isNotAccurateEnough($accuracy)) {
  263. $accuracy = $this->accuracyTypes[$accuracy];
  264. $minAccuracy = $this->accuracyTypes[$this->options['min_accuracy']];
  265. $this->setError(__('Accuracy not good enough (%s instead of at least %s)', $accuracy, $minAccuracy));
  266. $this->result = $result['result'];
  267. return false;
  268. }
  269. // save Result
  270. if ($this->options['log']) {
  271. CakeLog::write('geocode', __('Address \'%s\' has been geocoded', $latlng));
  272. }
  273. break;
  274. } elseif ($status == self::CODE_TOO_MANY_QUERIES) {
  275. // sent geocodes too fast, delay +0.1 seconds
  276. if ($this->options['log']) {
  277. CakeLog::write('geocode', __('Delay necessary for \'%s\'', $latlng));
  278. }
  279. $count++;
  280. } else {
  281. // something went wrong
  282. $this->setError('Error ' . $status . (isset($this->statusCodes[$status]) ? ' (' . $this->statusCodes[$status] . ')' : ''));
  283. if ($this->options['log']) {
  284. CakeLog::write('geocode', __('Could not geocode \'%s\'', $latlng));
  285. }
  286. return false; # for now...
  287. }
  288. if ($count > 5) {
  289. if ($this->options['log']) {
  290. CakeLog::write('geocode', __('Aborted after too many trials with \'%s\'', $latlng));
  291. }
  292. $this->setError(__('Too many trials - abort'));
  293. return false;
  294. }
  295. $this->pause(true);
  296. }
  297. $this->result = $result['result'];
  298. return true;
  299. }
  300. /**
  301. * Trying to avoid "TOO_MANY_QUERIES" error
  302. * @param boolean $raise If the pause length should be raised
  303. */
  304. public function pause($raise = false) {
  305. usleep($this->options['pause']);
  306. if ($raise) {
  307. $this->options['pause'] += 10000;
  308. }
  309. }
  310. /**
  311. * Actual querying
  312. *
  313. * @param string $address
  314. * @param array $params
  315. * @return boolean Success
  316. */
  317. public function geocode($address, $params = array()) {
  318. $this->reset(false);
  319. $this->debugSet('reverseGeocode', compact('address', 'params'));
  320. $this->setParams(array_merge($params, array('address' => $address)));
  321. if ($this->options['allow_inconclusive']) {
  322. // only host working with this setting?
  323. //$this->options['host'] = self::DEFAULT_HOST;
  324. }
  325. $count = 0;
  326. $requestUrl = $this->url();
  327. while (true) {
  328. $result = $this->_fetch($requestUrl);
  329. if ($result === false || $result === null) {
  330. $this->setError('Could not retrieve url');
  331. CakeLog::write('geocode', 'Geocoder could not retrieve url with \'' . $address . '\'');
  332. return false;
  333. }
  334. $this->debugSet('raw', $result);
  335. $result = $this->_transform($result);
  336. if (!is_array($result)) {
  337. $this->setError('Result parsing failed');
  338. CakeLog::write('geocode', __('Failed geocode parsing of \'%s\'', $address));
  339. return false;
  340. }
  341. $status = $result['status'];
  342. //debug(compact('result', 'requestUrl', 'success'));
  343. if ($status == self::CODE_SUCCESS) {
  344. // validate
  345. if (isset($result['results'][0]) && !$this->options['allow_inconclusive']) {
  346. $this->setError(__('Inconclusive result (total of %s)', count($result['results'])));
  347. $this->result = $result['results'];
  348. return false;
  349. }
  350. if (isset($result['results'][0])) {
  351. $result['result'] = $result['results'][0];
  352. }
  353. $accuracy = $this->_getMaxAccuracy($result['result']);
  354. if ($this->_isNotAccurateEnough($accuracy)) {
  355. $accuracyText = $this->accuracyTypes[$accuracy];
  356. $minAccuracy = $this->accuracyTypes[$this->options['min_accuracy']];
  357. $this->setError(__('Accuracy not good enough (%s instead of at least %s)', $accuracyText, $minAccuracy));
  358. $this->result = $result['result'];
  359. return false;
  360. }
  361. if (!empty($this->options['expect'])) {
  362. $fields = (empty($result['result']['types']) ? array() : Hash::filter($result['result']['types']));
  363. $found = array_intersect($fields, (array)$this->options['expect']);
  364. $validExpectation = !empty($found);
  365. if (!$validExpectation) {
  366. $this->setError(__('Expectation not reached (we have %s instead of at least %s)',
  367. implode(', ', $found),
  368. implode(', ', (array)$this->options['expect'])
  369. ));
  370. $this->result = $result['result'];
  371. return false;
  372. }
  373. }
  374. // save Result
  375. if ($this->options['log']) {
  376. CakeLog::write('geocode', __('Address \'%s\' has been geocoded', $address));
  377. }
  378. break;
  379. } elseif ($status == self::CODE_TOO_MANY_QUERIES) {
  380. // sent geocodes too fast, delay +0.1 seconds
  381. if ($this->options['log']) {
  382. CakeLog::write('geocode', __('Delay necessary for address \'%s\'', $address));
  383. }
  384. $count++;
  385. } else {
  386. // something went wrong
  387. $error_message = (isset($result['error_message']) ? $result['error_message'] : '');
  388. if (empty($error_message)) {
  389. $error_message = (isset($this->statusCodes[$status]) ? $this->statusCodes[$status] : '');
  390. }
  391. if (empty($error_message)) {
  392. $error_message = 'unknown';
  393. }
  394. $this->setError('Error ' . $status . ' (' . $error_message . ')');
  395. if ($this->options['log']) {
  396. CakeLog::write('geocode', __('Could not geocode \'%s\'', $address));
  397. }
  398. return false; # for now...
  399. }
  400. if ($count > 5) {
  401. if ($this->options['log']) {
  402. CakeLog::write('geocode', __('Aborted after too many trials with \'%s\'', $address));
  403. }
  404. $this->setError('Too many trials - abort');
  405. return false;
  406. }
  407. $this->pause(true);
  408. }
  409. $this->result = $result['result'];
  410. $this->result['all_results'] = $result['results'];
  411. return true;
  412. }
  413. /**
  414. * GeocodeLib::accuracyTypes()
  415. *
  416. * @param mixed $value
  417. * @return mixed Type or types
  418. */
  419. public function accuracyTypes($value = null) {
  420. if ($value !== null) {
  421. if (isset($this->accuracyTypes[$value])) {
  422. return $this->accuracyTypes[$value];
  423. }
  424. return null;
  425. }
  426. return $this->accuracyTypes;
  427. }
  428. /**
  429. * @return boolean $notAccurateEnough
  430. */
  431. protected function _isNotAccurateEnough($accuracy = null) {
  432. if (is_array($accuracy)) {
  433. $accuracy = $this->_getMaxAccuracy($accuracy);
  434. }
  435. if (empty($accuracy)) {
  436. $accuracy = 0;
  437. }
  438. // did we get a value instead of a key?
  439. if (in_array($accuracy, $this->accuracyTypes, true)) {
  440. $accuracy = array_search($accuracy, $this->accuracyTypes);
  441. }
  442. // validate key exists
  443. if (!array_key_exists($accuracy, $this->accuracyTypes)) {
  444. $accuracy = 0;
  445. }
  446. // is our current accuracy < minimum?
  447. return $accuracy < $this->options['min_accuracy'];
  448. }
  449. protected function _transform($record) {
  450. if ($this->options['output'] === 'json') {
  451. return $this->_transformJson($record);
  452. }
  453. return $this->_transformXml($record);
  454. }
  455. protected function _transformJson($record) {
  456. if (!is_array($record)) {
  457. $record = json_decode($record, true);
  458. }
  459. return $this->_transformData($record);
  460. }
  461. protected function _transformXml($record) {
  462. if (!is_array($record)) {
  463. $xml = Xml::build($record);
  464. $record = Xml::toArray($xml);
  465. if (array_key_exists('GeocodeResponse', $record)) {
  466. $record = $record['GeocodeResponse'];
  467. }
  468. }
  469. return $this->_transformData($record);
  470. }
  471. /**
  472. * Try to find the max accuracy level
  473. * - look through all fields and
  474. * attempt to find the first record which matches an accuracyTypes field
  475. *
  476. * @param array $record
  477. * @return int $maxAccuracy 9-0 as defined in $this->accuracyTypes
  478. */
  479. public function _getMaxAccuracy($record) {
  480. if (!is_array($record)) {
  481. return null;
  482. }
  483. $accuracyTypes = $this->accuracyTypes;
  484. $accuracyTypes = array_reverse($accuracyTypes, true);
  485. foreach ($accuracyTypes as $key => $field) {
  486. if (array_key_exists($field, $record) && !empty($record[$field])) {
  487. // found $field -- return it's $key
  488. return $key;
  489. }
  490. }
  491. // not found? recurse into all possible children
  492. foreach (array_keys($record) as $key) {
  493. if (empty($record[$key]) || !is_array($record[$key])) {
  494. continue;
  495. }
  496. $accuracy = $this->_getMaxAccuracy($record[$key]);
  497. if ($accuracy !== null) {
  498. // found in nested value
  499. return $accuracy;
  500. }
  501. }
  502. return null;
  503. }
  504. /**
  505. * Flattens result array and returns clean record
  506. * keys:
  507. * - formatted_address, type, country, country_code, country_province, country_province_code, locality, sublocality, postal_code, route, lat, lng, location_type, viewport, bounds
  508. *
  509. * @param mixed $record any level of input, whole raw array or records or single record
  510. * @return array $record organized & normalized
  511. */
  512. public function _transformData($record) {
  513. if (!is_array($record)) {
  514. return $record;
  515. }
  516. if (!array_key_exists('address_components', $record)) {
  517. foreach (array_keys($record) as $key) {
  518. $record[$key] = $this->_transformData($record[$key]);
  519. }
  520. return $record;
  521. }
  522. $res = array();
  523. // handle and organize address_components
  524. $components = array();
  525. if (!isset($record['address_components'][0])) {
  526. $record['address_components'] = array($record['address_components']);
  527. }
  528. foreach ($record['address_components'] as $c) {
  529. $types = array();
  530. if (isset($c['types'])) { //!is_array($c['Type'])
  531. if (!is_array($c['types'])) {
  532. $c['types'] = (array)$c['types'];
  533. }
  534. $type = $c['types'][0];
  535. array_shift($c['types']);
  536. $types = $c['types'];
  537. } elseif (isset($c['types'])) {
  538. $type = $c['types'];
  539. } else {
  540. // error?
  541. continue;
  542. }
  543. if (array_key_exists($type, $components)) {
  544. $components[$type]['name'] .= ' ' . $c['long_name'];
  545. $components[$type]['abbr'] .= ' ' . $c['short_name'];
  546. $components[$type]['types'] += $types;
  547. }
  548. $components[$type] = array('name' => $c['long_name'], 'abbr' => $c['short_name'], 'types' => $types);
  549. }
  550. $res['formatted_address'] = $record['formatted_address'];
  551. if (array_key_exists('country', $components)) {
  552. $res['country'] = $components['country']['name'];
  553. $res['country_code'] = $components['country']['abbr'];
  554. } else {
  555. $res['country'] = $res['country_code'] = '';
  556. }
  557. if (array_key_exists('administrative_area_level_1', $components)) {
  558. $res['country_province'] = $components['administrative_area_level_1']['name'];
  559. $res['country_province_code'] = $components['administrative_area_level_1']['abbr'];
  560. } else {
  561. $res['country_province'] = $res['country_province_code'] = '';
  562. }
  563. if (array_key_exists('postal_code', $components)) {
  564. $res['postal_code'] = $components['postal_code']['name'];
  565. } else {
  566. $res['postal_code'] = '';
  567. }
  568. if (array_key_exists('locality', $components)) {
  569. $res['locality'] = $components['locality']['name'];
  570. } else {
  571. $res['locality'] = '';
  572. }
  573. if (array_key_exists('sublocality', $components)) {
  574. $res['sublocality'] = $components['sublocality']['name'];
  575. } else {
  576. $res['sublocality'] = '';
  577. }
  578. if (array_key_exists('route', $components)) {
  579. $res['route'] = $components['route']['name'];
  580. if (array_key_exists('street_number', $components)) {
  581. $res['route'] .= ' ' . $components['street_number']['name'];
  582. }
  583. } else {
  584. $res['route'] = '';
  585. }
  586. // determine accuracy types
  587. if (array_key_exists('types', $record)) {
  588. $res['types'] = $record['types'];
  589. } else {
  590. $res['types'] = array();
  591. }
  592. //TODO: add more
  593. $res['lat'] = $record['geometry']['location']['lat'];
  594. $res['lng'] = $record['geometry']['location']['lng'];
  595. $res['location_type'] = $record['geometry']['location_type'];
  596. if (!empty($record['geometry']['viewport'])) {
  597. $res['viewport'] = array('sw' => $record['geometry']['viewport']['southwest'], 'ne' => $record['geometry']['viewport']['northeast']);
  598. }
  599. if (!empty($record['geometry']['bounds'])) {
  600. $res['bounds'] = array('sw' => $record['geometry']['bounds']['southwest'], 'ne' => $record['geometry']['bounds']['northeast']);
  601. }
  602. // manuell corrections
  603. $array = array(
  604. 'Berlin' => 'BE',
  605. );
  606. if (!empty($res['country_province_code']) && array_key_exists($res['country_province_code'], $array)) {
  607. $res['country_province_code'] = $array[$res['country_province_code']];
  608. }
  609. // inject maxAccuracy for transparency
  610. $res['maxAccuracy'] = $this->_getMaxAccuracy($res);
  611. return $res;
  612. }
  613. /**
  614. * Fetches url with curl if available
  615. * fallbacks: cake and php
  616. * note: expects url with json encoded content
  617. *
  618. * @return mixed
  619. **/
  620. protected function _fetch($url) {
  621. $this->HttpSocket = new HttpSocketLib($this->use);
  622. $this->debugSet('_fetch', $url);
  623. if ($res = $this->HttpSocket->fetch($url, 'CakePHP Geocode Lib')) {
  624. return $res;
  625. }
  626. $this->setError($this->HttpSocket->error());
  627. return false;
  628. }
  629. /**
  630. * return debugging info
  631. *
  632. * @return array $debug
  633. */
  634. public function debug() {
  635. $this->debug['result'] = $this->result;
  636. return $this->debug;
  637. }
  638. /**
  639. * set debugging info
  640. *
  641. * @param string $key
  642. * @param mixed $data
  643. * @return void
  644. */
  645. public function debugSet($key, $data = null) {
  646. $this->debug[$key] = $data;
  647. }
  648. /**
  649. * Calculates Distance between two points - each: array('lat'=>x,'lng'=>y)
  650. * DB:
  651. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  652. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  653. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  654. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  655. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  656. 'AS distance'
  657. *
  658. * @param array pointX
  659. * @param array pointY
  660. * @param float $unit (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet)
  661. * @return integer distance: in km
  662. */
  663. public function distance(array $pointX, array $pointY, $unit = null) {
  664. if (empty($unit) || !array_key_exists(($unit = strtoupper($unit)), $this->units)) {
  665. $unit = array_keys($this->units);
  666. $unit = $unit[0];
  667. }
  668. $res = $this->calculateDistance($pointX, $pointY);
  669. if (isset($this->units[$unit])) {
  670. $res *= $this->units[$unit];
  671. }
  672. return ceil($res);
  673. }
  674. /**
  675. * GeocodeLib::calculateDistance()
  676. *
  677. * @param array $pointX
  678. * @param array $pointY
  679. * @return float
  680. */
  681. public static function calculateDistance(array $pointX, array $pointY) {
  682. /*
  683. $res = 6371.04 * ACOS( COS( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  684. COS( PI()/2 - rad2deg(90 - $pointY['lat'])) *
  685. COS( rad2deg($pointX['lng']) - rad2deg($pointY['lng'])) +
  686. SIN( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  687. SIN( PI()/2 - rad2deg(90 - $pointY['lat'])));
  688. $res = 6371.04 * acos(sin($pointY['lat'])*sin($pointX['lat'])+cos($pointY['lat'])*cos($pointX['lat'])*cos($pointY['lng'] - $pointX['lng']));
  689. */
  690. // seems to be the only working one (although slightly incorrect...)
  691. $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']))));
  692. return $res;
  693. }
  694. /**
  695. * Convert between units
  696. *
  697. * @param float $value
  698. * @param char $fromUnit (using class constants)
  699. * @param char $toUnit (using class constants)
  700. * @return float convertedValue
  701. * @throws CakeException
  702. */
  703. public function convert($value, $fromUnit, $toUnit) {
  704. if (!isset($this->units[($fromUnit = strtoupper($fromUnit))]) || !isset($this->units[($toUnit = strtoupper($toUnit))])) {
  705. throw new CakeException(__('Invalid Unit'));
  706. }
  707. if ($fromUnit === 'M') {
  708. $value *= $this->units[$toUnit];
  709. } elseif ($toUnit === 'M') {
  710. $value /= $this->units[$fromUnit];
  711. } else {
  712. $value /= $this->units[$fromUnit];
  713. $value *= $this->units[$toUnit];
  714. }
  715. return $value;
  716. }
  717. /**
  718. * Fuzziness filter for coordinates (lat or lng).
  719. * Useful if you store other users' locations and want to grant some
  720. * privacy protection. This way the coordinates will be slightly modified.
  721. *
  722. * @param float coord
  723. * @param integer level (0 = nothing to 5 = extrem)
  724. * - 1:
  725. * - 2:
  726. * - 3:
  727. * - 4:
  728. * - 5:
  729. * @throws CakeException
  730. * @return float coord
  731. */
  732. public static function blur($coord, $level = 0) {
  733. if (!$level) {
  734. return $coord;
  735. }
  736. //TODO:
  737. switch ($level) {
  738. case 1:
  739. break;
  740. case 2:
  741. break;
  742. case 3:
  743. break;
  744. case 4:
  745. break;
  746. case 5:
  747. break;
  748. default:
  749. throw new CakeException(__('Invalid level \'%s\'', $level));
  750. }
  751. $scrambleVal = 0.000001 * mt_rand(1000, 2000) * (mt_rand(0, 1) === 0 ? 1 : -1);
  752. return ($coord + $scrambleVal);
  753. //$scrambleVal *= (mt_rand(0,1) === 0 ? 1 : 2);
  754. //$scrambleVal *= (float)(2^$level);
  755. // TODO: + - by chance!!!
  756. return $coord + $scrambleVal;
  757. }
  758. const TYPE_ROOFTOP = 'ROOFTOP';
  759. const TYPE_RANGE_INTERPOLATED = 'RANGE_INTERPOLATED';
  760. const TYPE_GEOMETRIC_CENTER = 'GEOMETRIC_CENTER';
  761. const TYPE_APPROXIMATE = 'APPROXIMATE';
  762. const CODE_SUCCESS = 'OK'; //200;
  763. const CODE_TOO_MANY_QUERIES = 'OVER_QUERY_LIMIT'; //620;
  764. const CODE_BAD_REQUEST = 'REQUEST_DENIED'; //400;
  765. const CODE_MISSING_QUERY = 'INVALID_REQUEST';//601;
  766. const CODE_UNKNOWN_ADDRESS = 'ZERO_RESULTS'; //602;
  767. /*
  768. const CODE_SERVER_ERROR = 500;
  769. const CODE_UNAVAILABLE_ADDRESS = 603;
  770. const CODE_UNKNOWN_DIRECTIONS = 604;
  771. const CODE_BAD_KEY = 610;
  772. */
  773. }
  774. /*
  775. TODO:
  776. http://code.google.com/intl/de-DE/apis/maps/documentation/geocoding/
  777. - whats the difference to "http://maps.google.com/maps/api/geocode/output?parameters"
  778. */
  779. /*
  780. Example: NEW:
  781. Array
  782. (
  783. [status] => OK
  784. [Result] => Array
  785. (
  786. [type] => postal_code
  787. [formatted_address] => 74523, Deutschland
  788. [AddressComponent] => Array
  789. (
  790. [0] => Array
  791. (
  792. [long_name] => 74523
  793. [short_name] => 74523
  794. [type] => postal_code
  795. )
  796. [1] => Array
  797. (
  798. [long_name] => Schwaebisch Hall
  799. [short_name] => SHA
  800. [Type] => Array
  801. (
  802. [0] => administrative_area_level_2
  803. [1] => political
  804. )
  805. )
  806. [2] => Array
  807. (
  808. [long_name] => Baden-Wuerttemberg
  809. [short_name] => BW
  810. [Type] => Array
  811. (
  812. [0] => administrative_area_level_1
  813. [1] => political
  814. )
  815. )
  816. [3] => Array
  817. (
  818. [long_name] => Deutschland
  819. [short_name] => DE
  820. [Type] => Array
  821. (
  822. [0] => country
  823. [1] => political
  824. )
  825. )
  826. )
  827. [Geometry] => Array
  828. (
  829. [Location] => Array
  830. (
  831. [lat] => 49.1257616
  832. [lng] => 9.7544127
  833. )
  834. [location_type] => APPROXIMATE
  835. [Viewport] => Array
  836. (
  837. [Southwest] => Array
  838. (
  839. [lat] => 49.0451477
  840. [lng] => 9.6132550
  841. )
  842. [Northeast] => Array
  843. (
  844. [lat] => 49.1670260
  845. [lng] => 9.8756350
  846. )
  847. )
  848. [Bounds] => Array
  849. (
  850. [Southwest] => Array
  851. (
  852. [lat] => 49.0451477
  853. [lng] => 9.6132550
  854. )
  855. [Northeast] => Array
  856. (
  857. [lat] => 49.1670260
  858. [lng] => 9.8756350
  859. )
  860. )
  861. )
  862. )
  863. )
  864. Example OLD:
  865. Array
  866. (
  867. [name] => 74523 Deutschland
  868. [Status] => Array
  869. (
  870. [code] => 200
  871. [request] => geocode
  872. )
  873. [Result] => Array
  874. (
  875. [id] => p1
  876. [address] => 74523, Deutschland
  877. [AddressDetails] => Array
  878. (
  879. [Accuracy] => 5
  880. [xmlns] => urn:oasis:names:tc:ciq:xsdschema:xAL:2.0
  881. [Country] => Array
  882. (
  883. [CountryNameCode] => DE
  884. [CountryName] => Deutschland
  885. [AdministrativeArea] => Array
  886. (
  887. [AdministrativeAreaName] => Baden-Wuerttemberg
  888. [SubAdministrativeArea] => Array
  889. (
  890. [SubAdministrativeAreaName] => Schwaebisch Hall
  891. [PostalCode] => Array
  892. (
  893. [PostalCodeNumber] => 74523
  894. )
  895. )
  896. )
  897. )
  898. )
  899. [ExtendedData] => Array
  900. (
  901. [LatLonBox] => Array
  902. (
  903. [north] => 49.1670260
  904. [south] => 49.0451477
  905. [east] => 9.8756350
  906. [west] => 9.6132550
  907. )
  908. )
  909. [Point] => Array
  910. (
  911. [coordinates] => 9.7544127,49.1257616,0
  912. )
  913. )
  914. ) {
  915. "status": "OK",
  916. "results": [ {
  917. "types": [ "street_address" ],
  918. "formatted_address": "Krebenweg 20, 74523 Schwäbisch Hall, Deutschland",
  919. "address_components": [ {
  920. "long_name": "20",
  921. "short_name": "20",
  922. "types": [ "street_number" ]
  923. }, {
  924. "long_name": "Krebenweg",
  925. "short_name": "Krebenweg",
  926. "types": [ "route" ]
  927. }, {
  928. "long_name": "Bibersfeld",
  929. "short_name": "Bibersfeld",
  930. "types": [ "sublocality", "political" ]
  931. }, {
  932. "long_name": "Schwäbisch Hall",
  933. "short_name": "Schwäbisch Hall",
  934. "types": [ "locality", "political" ]
  935. }, {
  936. "long_name": "Schwäbisch Hall",
  937. "short_name": "SHA",
  938. "types": [ "administrative_area_level_2", "political" ]
  939. }, {
  940. "long_name": "Baden-Württemberg",
  941. "short_name": "BW",
  942. "types": [ "administrative_area_level_1", "political" ]
  943. }, {
  944. "long_name": "Deutschland",
  945. "short_name": "DE",
  946. "types": [ "country", "political" ]
  947. }, {
  948. "long_name": "74523",
  949. "short_name": "74523",
  950. "types": [ "postal_code" ]
  951. } ],
  952. "geometry": {
  953. "location": {
  954. "lat": 49.0817369,
  955. "lng": 9.6908451
  956. },
  957. "location_type": "RANGE_INTERPOLATED", //ROOFTOP //APPROXIMATE
  958. "viewport": {
  959. "southwest": {
  960. "lat": 49.0785954,
  961. "lng": 9.6876999
  962. },
  963. "northeast": {
  964. "lat": 49.0848907,
  965. "lng": 9.6939951
  966. }
  967. },
  968. "bounds": {
  969. "southwest": {
  970. "lat": 49.0817369,
  971. "lng": 9.6908451
  972. },
  973. "northeast": {
  974. "lat": 49.0817492,
  975. "lng": 9.6908499
  976. }
  977. }
  978. },
  979. "partial_match": true
  980. } ]
  981. }
  982. */