GeocodeLib.php 27 KB

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