GeocodeLib.php 27 KB

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