Geocoding using PHP and Google maps API V3

Geocoding is the process of converting an address to a lat/long set of coordinates for mapping against the google maps api (or the other way around ie: coords to address).  This used to be quite a long winded job exploding arrays and all kinds of jazz in the older Google Maps API’s however as of V3 its become incrediably simple when using PHP to quickly request and retrieve the coordinates from an input address.

I’m not going to go into massive details explaining it as its mostly commented in the code you can also find more information direct from google on their maps API page including a full list of status codes and a complete breakdown of the returned XML feed.

For our request we’ll be using the PHP built in function simplexml_load_file().

$postcode = urlencode("DN4 6HP"); // post code to look up in this case status however can easily be retrieved from a database or a form post
    $request_url = "".$postcode."&sensor=true"; // the request URL you'll send to google to get back your XML feed
    $xml = simplexml_load_file($request_url) or die("url not loading");// XML request
    $status = $xml->status;// GET the request status as google's api can return several responses
    if ($status=="OK") {
        //request returned completed time to get lat / lang for storage
        $lat = $xml->result->geometry->location->lat;
        $long = $xml->result->geometry->location->lng;
        echo "$lat,$long";  //spit out results or you can store them in a DB if you wish
    if ($status=="ZERO_RESULTS") {
        //indicates that the geocode was successful but returned no results. This may occur if the geocode was passed a non-existent address or a latlng in a remote location.
    if ($status=="OVER_QUERY_LIMIT") {
        //indicates that you are over your quota of geocode requests against the google api
    if ($status=="REQUEST_DENIED") {
        //indicates that your request was denied, generally because of lack of a sensor parameter.
    if ($status=="INVALID_REQUEST") {
        //generally indicates that the query (address or latlng) is missing.

Thats it as simple as that I’ve put in the traps for the different status returns from google however not done anything with them apart from comment them its upto you how you make your application fallback.



Published by


FC Software Technical Director