PHP Geocoding tutorial with the Google Maps API – Part One

So unless you live under a non-Web 2.0-enabled rock, you’ve probably heard of the magic of the Google maps API and google maps mashups. If you’re saavy, you’ve probably even heard that now Google Maps offer translation of addresses into latitude and longitude, aka Geocoding.

What you may not know is that the folks at google exposed this geocoding as a regular old URL-based webservice, which means that whatever Nifty mashups your devious little minds can come up with (as long as they fly with google’s TOS) can be powered on the backend without ever loading a google map!

So lets cut the chit-chat and jump to some code… I’m going to use PHP here, but do whatever fuels your nerding.

First, sign up for a key, put in whatever URL you happen to own, it won’t matter (i’ll explain later).

next, add this to your php file, making SURE to replace the key with your own:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?
//Three parts to the querystring: q is address, output is the format, key is the GAPI key
$key = "YOUR KEY HERE";
$address = urlencode("columbia MO");
 
//If you want an extended data set, change the output to "xml" instead of csv
$url = "http://maps.google.com/maps/geo?q=".$address."&output=csv&key=".$key;
//Set up a CURL request, telling it not to spit back headers, and to throw out a user agent.
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0); //Change this to a 1 to return headers
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$data = curl_exec($ch);
curl_close($ch);
 
echo "Data: ". $data;
?>

Supposing all goes well you should see the following: (if not check the PHP CURL manual)

Data: 200,4,38.951667,-92.333889

You’ll notice that the first number is the return code, the second the relative accuracy (there 4 we see here is quite low as a result of the broad input. 8 is street-level address accuracy), third the latitude, and fourth the longitude.

So now that we’ve seen the magic.. let’s get it all nicely formatted:

1
2
3
4
5
6
7
8
9
10
11
12
//Check our Response code to ensure success
if (substr($data,0,3) == "200")
{
$data = explode(",",$data);
 
$precision = $data[1];
$latitude = $data[2];
$longitude = $data[3];
 
} else {
echo "Error in geocoding! Http error ".substr($data,0,3);
}

And that’s it! Less than 40 lines of code to give you a powerful resource for mapping and usability. Just how powerful? You’ll have to wait for part two to find out…

*Note on locations and API keys: In my experience thus far, the Geocoding service doesn’t actually check that the api key is being called from the originating server. This may change in the future at some point, so keep your eyes open.
FULL CODE LISTING:

<?
//Set up our variables
$longitude = "";
$latitude = "";
$precision = "";
 
//Three parts to the querystring: q is address, output is the format (
$key = "YOUR KEY HERE";
$address = urlencode("columbia MO");
$url = "http://maps.google.com/maps/geo?q=".$address."&amp;output=csv&amp;key=".$key;
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$data = curl_exec($ch);
curl_close($ch);
 
echo "Data: ". $data."&lt;br&gt;";
//Check our Response code to ensure success
if (substr($data,0,3) == "200")
{
$data = explode(",",$data);
 
$precision = $data[1];
$latitude = $data[2];
$longitude = $data[3];
 
echo "Latutide: ".$latitude."&lt;br&gt;";
 
echo "Longitude: ".$longitude."&lt;br&gt;";
 
} else {
echo "Error in geocoding! Http error ".substr($data,0,3);
}
 
?>

Update:

A few people have mentioned that after some number of requests (between 100-300) in quick succession google will kill your access for the day, so you may want to insert a

sleep(1);

To stagger the requests a little.

Tags: , ,

12 Comments on “PHP Geocoding tutorial with the Google Maps API – Part One”

  1. designing4u.de » Geolocation class - retrieving longitude and latitude using google maps

    [...] really nice way, how to accomplish that. On Tim Shower’s homepage I have found a really nice php geocoding tutorial, which I used to build my solution. For our purposes we will use client for URL (cURL) to retrieve [...]

  2. Google Maps Tutorials | ogeeBloggin

    [...] PHP Geocoding tutorial with the Google Maps API – Part One [...]

  3. Alan Jackson

    Tim,

    Many thanks. I have tried many ways to do exactly this. My PHP is on an up an coming level so far. I got to the point in my head of what I needed to retrieve, the fact that I would need to explode it and got an URL working just didn’t know how to go about getting the information from Google.

    With this code I feel I can finally get over that “hump”.

    -Alan

  4. Kailash Dave

    Many thanks Sir :)
    It is realy very helpful for the developers to done with the integration part without waisting much to do so :)

    Regards

    KD

  5. Kurt Reinholtz

    Very nice, thank you. Elegant solution saved me a lot of time. Very much appreciated!

  6. Hung Nguyen

    This is what i’ve been looking for, you save my day

    LEGEND!

  7. GeoCoding in PHP | Things I Forgot

    [...] an excellent article by Tim Showers, here are my notes on [...]

  8. Ray

    You beautiful little coder you, it still works, thanks so far. But where would I put the sleep(1); command? I do not really see any place to put it where it would cause any effect. As I imagine the 300 are accessing the site each second, thus making the whole process an instant kill victim by Google. I’d have to split up the requests among and route them to a couple of dozen physically different servers returning the geocoding results, to make the kill access menace go away theoretically.

  9. Chicago Web Developer

    HERE IS UPDATED CODE SINCE THE API HAS CHANGED!

    <?
    //Set up our variables
    $longitude = "";
    $latitude = "";
    $precision = "";

    //Three parts to the querystring: q is address, output is the format (
    $key = "YOUR API KEY HERE";
    $address = urlencode("columbia MO");
    $url = "http://maps.google.com/maps/geo?q=".$address."&output=csv&key=".$key;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    $geo_json = json_decode($data, true);

    print_r($geo_json);

    if ($geo_json['Status']['code'] == '200') {

    $precision = $geo_json['Placemark'][0]['AddressDetails']['Accuracy'];
    $latitude = $geo_json['Placemark'][0]['Point']['coordinates'][0];
    $longitude = $geo_json['Placemark'][0]['Point']['coordinates'][1];

    echo "Precision: $precision \n";
    echo "Latutide: $latitude \n";
    echo "Longitude: $longitude \n";

    } else {
    echo "Error in geocoding! Http error ".substr($data,0,3);
    }

  10. Stu D'Alessandro

    Chicago, I believe you want to specify json as the output format, otherwise looks great.

    $url = “http://maps.google.com/maps/geo?q=”.$address.”&output=json&key=”.$key;

    Thanks Tim et al for a super helpful article!!

  11. Brad Wedell

    I just released an updated version of the PHPGoogleMapAPI (which I have coined PHPGoogleMapAPIv3). The original version from Monte Ohrt was pretty powerful, and I have gone ahead and updated it to use the new V3 of the Google Maps APIs. With this class, if you wanted to do a geocoding request, you would simply do:

    $map_object = new GoogleMapAPI();
    $geo_coords = $map_object->getGeocode($address);

    if( $geo_coords != false ){
    echo $geo_coords["lat"];
    echo $geo_coords["lon"];
    }

    The code can be found at http://code.google.com/p/phpgooglemapapiv3/

  12. Brad Wedell

    Quick update, have spoken with Monte and have changed the URL for the Google Code repository: the new url is http://code.google.com/p/php-google-map-api – sorry for the confusion!

Leave a Reply