GeocodeLib.php 27 KB

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