Monthly Archive for October, 2008

Get Geocodes From Addresses

So you have an address for a location, or maybe a bunch of addresses for different locations, and you want to use Google’s Map API to draw a map with icons for all the locations. Thing is, Google’s Map API requires that you know the latitude and longitude, not the address. You could go and look these up, one at a time, manually. Or you could use a batch geocoder. But maybe you want a programmatic solution. You want to do something like:

$geocode = getGeocode($fullAddress);

Here’s the getGeocode function:

/* get the geocode for a particular address
* @param string the full address on one line
* @return string geocode like x,y
*/
function getGeocode($address) {
 
$address_url = urlencode($address);
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.domain.com/path/to/getGeocode.php?address=" . $address_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$geocode = curl_exec($ch);
curl_close($ch);
 
return $geocode;
 
}

And then you’ll need this file to go out and get the geocodes:

$address = $_REQUEST['address'];
$address_url = urlencode($address);
 
$key = 'your-google-map-api-key-here';
$geo = 'http://maps.google.com/maps/geo?q=' . $address_url . '&output=xml&key=' . $key;
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $geo);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$getback = curl_exec($ch);
curl_close($ch);
 
$xml = simplexml_load_string($getback);
echo $xml->Response[0]->Placemark->Point->coordinates;

If you felt like tinkering, you could dump that xml out and have a look at it. There’s a “status” field which you could make use of.

You’re going to get a string back that looks something like “a,b,c” and each value is a number. The last one is often 0. I’m sure this has something to do with how accurate these points are. All you really care about are the first two numbers. And I *think* those are backwards. You define a GLatLng by passing latitude, then longitude, but I think their geocoder returns longitude, then latitude. So you may have to do some manipulating.

In general, Google says making requests like this is time and resource intensive. If you had a database of 60 something addresses that you wanted to put on a map, it is going to be a little slow to run all of those. In my opinion, it would be better to stores the geocodes in the database, and make your address forms handle it.