How to use Google HTTP Geocoding

Google Maps - Edmonton

Getting the Latitude and Longitude of an address using the Google Maps API is actually quite easy.

Google makes this process easy buy letting us interact with their API using a URI via a HTTP Request.

By using a PHP function called urlencode I take the Address values and convert spaces to underscores so your URI won’t explode and make Google angry.

Google is nice enough to give us formatted XML, KML, CSV, and even JSON. The basic URL looks something like this http://maps.google.com/maps/geo?q=address+city+state&output=xml using a plus (+) signal the next field like City, Province, or Postal Code.

Click to see output example.

In my application all my contact information is stored in a Database, when I save or update a contact I generate the URL and bring back some XML to work with.


   $googleAddress = "http://maps.google.com/maps/geo?q=";.urlencode($address) .'+'. urlencode($city) .'+'. urlencode($province).'+'. urlencode($country)."&output=xml";

The next task was to get the contents of the file, for this I use the “file_get_contents” function and pass it my URL.


   $googlePage = file_get_contents($googleAddress);

PHP has a neat little function called SimpleXMLElement that will convert XML to an object.

Note: The SimpleXMLElement will only work in PHP 5+.


$xml = new SimpleXMLElement($googlePage);

Now that we have the values from the XML we can assign variables to them that will allow us to display the results.

http://ca.php.net/xml


list($longitude, $latitude, $altitude) = explode(",", $xml->Response->Placemark->Point->coordinates);

At this point you can use the information and store it in a database as I did, Or just echo it out.


echo "Longitude: $longitude, Latitude: $latitude";

Here is the full code:


$address = '1 Sir Winston Churchill Square';
$city = 'edmonton';
$province = 'alberta';
$country = 'canada';
$postalcode = 'T5J 2R7';

// Google Geo Address
$googleAddress = "http://maps.google.com/maps/geo?q=";.urlencode($address) .'+'. urlencode($city) .'+'. urlencode($province).'+'. urlencode($postalcode).'+'. urlencode($country)."&output=xml";

// Retrieve the URL contents
$googlePage = file_get_contents($googleAddress);

// Parse the returned XML file
$xml = new SimpleXMLElement($googlePage);

// Parse the coordinate string
list($longitude, $latitude, $altitude) = explode(",", $xml->Response->Placemark->Point->coordinates);

// Output the coordinates
echo "Longitude: $longitude, Latitude: $latitude";

Links:
Google Geocoding HTTP Request

Signup for my mailing list

Receive other rambings like this on design, code, and some times food.