class GeocodeAddress
{
private $address;
private $latitude;
private $longitude;
private $error;
private $error_msg;
public function __construct($address) {
$this->address = $address;
$this->Geocode();
}
private function Geocode() {
$this->error = false;
$this->error_msg = '';
if(!is_string($this->address))
die("All addresses must be passed as a string");
$url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($this->address));
$_result = false;
if($_result = file_get_contents($url)) {
if(strpos($_result, 'errortips') > 1 || strpos($_result,'Did you mean:') !== false) {
$this->error = true;
$this->error_msg = 'Unable to geocode this address. Please check the address is correctly formatted';
}
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$this->latitude = $_match[1];
$this->longitude = $_match[2];
}
}
public function GetLatitude() {
if($this->error !== false)
return 'ERROR : '.$this->error_msg;
else
return $this->latitude;
}
public function GetLongitude() {
if($this->error !== false)
return 'ERROR : '.$this->error_msg;
else
return $this->longitude;
}
public function GetAddress() { return $this->address; }
}