This is a little experiment with the Google Geocoding service. Geocoding is the process of turning human readable addresses into a latitude and longitude. Google provide a free web service to let you do this very easily.
As a supporting utlity for the Google Maps service, Google Geocoding is a very handy mechanism for easily obtaining the latitude and longitude of pretty much any point on the planet.
To do the geocoding calls I have a simple class that has a couple of methods like this:
public function query($location)
{
$url = $this->_queryUrl($location);
$xml = simplexml_load_file($url);
if (false == ($xml instanceof SimpleXMLElement))
{
throw new Google_Exception('Geocoding api call failed');
}
$response = new Geocoding_Response($url, $xml);
return $response;
}
protected function _queryUrl($location)
{
$key = $this->getApiKey();
$url = 'http://' . self::$_BaseUrl . '/maps/geo?output=xml&oe=utf-8&key' . $key . '&q=' . $location;
return $url;
}
I also have a little response class to wrap and parse the XML data. Its very basic but you could make it do all sorts of things.
class Geocoding_Response
{
protected $_url;
protected $_xml;
protected $_error;
protected $_responseError;
protected $_coords;
public function __construct($url, SimpleXMLElement $xml)
{
$this->_url = $url;
$this->_coords = array();
$this->_processXml($xml);
}
public function hasError()
{
return $this->_error;
}
public function responseError()
{
return $this->_responseError;
}
public function lat()
{
return $this->_coords['lat'];
}
public function lng()
{
return $this->_coords['lng'];
}
public function url()
{
return $this->_url;
}
public function __toString()
{
return implode(', ', $this->_coords);
}
protected function _processXml(SimpleXMLElement $xml)
{
$this->_xml = $xml;
if (200 != (int) $xml->Response->Status->code)
{
$this->_error = true;
$this->_responseError = $this->_statusMessage((int) $xml->Response->Status);
}
list($lng, $lat) = explode(',', (string) $this->_xml->Response->Placemark->Point->coordinates);
$this->_coords = array('lat' => $lat, 'lng' => $lng);
return true;
}
protected function _statusMessage($status)
{
switch ($status)
{
case 200:
return 'ok';
case 400:
return 'bad request';
case 500:
return 'internal error';
case 601:
return 'no location provided';
case 602:
return 'location not found';
case 603:
return 'location unavailable';
case 604:
return 'unknown directions';
case 610:
return 'bad api key';
case 620:
return 'too many queries';
default:
return 'Unknown error';
}
}
}
To do some geocoding you first get a Google Maps API key (slightly odd since we're doing this server side but still...). Then you would use the above code like this:
$location = '10 Downing Street, London';
$geo = new Google_Geocoding($apiKey);
try {
$response = $geo->query($location);
echo $response;
}
catch (Google_Exception $ex) {
echo "Error";
}
There's a demo of this code working here.