PHP Geocode Address Snippet


SUBMITTED BY: Guest

DATE: July 9, 2013, 7:18 a.m.

FORMAT: PHP

SIZE: 1.5 kB

HITS: 957

  1. class GeocodeAddress
  2. {
  3. private $address;
  4. private $latitude;
  5. private $longitude;
  6. private $error;
  7. private $error_msg;
  8. public function __construct($address) {
  9. $this->address = $address;
  10. $this->Geocode();
  11. }
  12. private function Geocode() {
  13. $this->error = false;
  14. $this->error_msg = '';
  15. if(!is_string($this->address))
  16. die("All addresses must be passed as a string");
  17. $url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($this->address));
  18. $_result = false;
  19. if($_result = file_get_contents($url)) {
  20. if(strpos($_result, 'errortips') > 1 || strpos($_result,'Did you mean:') !== false) {
  21. $this->error = true;
  22. $this->error_msg = 'Unable to geocode this address. Please check the address is correctly formatted';
  23. }
  24. preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
  25. $this->latitude = $_match[1];
  26. $this->longitude = $_match[2];
  27. }
  28. }
  29. public function GetLatitude() {
  30. if($this->error !== false)
  31. return 'ERROR : '.$this->error_msg;
  32. else
  33. return $this->latitude;
  34. }
  35. public function GetLongitude() {
  36. if($this->error !== false)
  37. return 'ERROR : '.$this->error_msg;
  38. else
  39. return $this->longitude;
  40. }
  41. public function GetAddress() { return $this->address; }
  42. }

comments powered by Disqus