How to cache google maps geocodes
I've been working a lot with the google maps API lately. It's fun working with and is one of the easier API's I've worked with. One nice feature of the map system is the ability to geocode variables, which can be done on the fly by the viewers browser while s/he looks at the page.
Unfortunately there is a limit to 500k geocodes per day.
With the site I am working with, and the number of items displayed on the page, that would limit me to 600 page views per day, far below the expected turnout (1000x smaller than the expected pageviews on an upcoming project as well!).
After searching through the documentation I found a URL schema which returns latitude longitude pairs for addresses using the address and API key as input. This returns either XML, CSV or JSON. CSV is all I need for this simple project (saves bandwidth at least).
Here is the script I came up with to geocode an entire database of addresses. This can be altered a lot to suite your needs. For example, when a new address is added to the DB, you would only need to geocode that particular address. This script includes no error handling and is meant to be as simple as possible.
Released under the GPL, have fun with it (-:
<?php
include("MYSQL CONNECTION FILE");
$sql = "SELECT id, address FROM locations";
$api_key = "API KEY";
$city_string = ",+City,+ST+ZZZZZ";
$result = runQuery($sql);
while ($row = mysql_fetch_assoc($result)) {
$address = urlencode($row['address']);
$url = "http://maps.google.com/maps/geo?q=
{$address}{$city_string}&output=csv&key={$api_key}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$document = curl_exec($ch);
curl_close($ch);
echo "<div><b>{$row['address']}</b> - $document</div>\n";
list($r, $a, $lat, $lon) = explode(",",$document);
runQuery("UPDATE locations SET latitude = '$lat',
longitude = '$lon' WHERE id = {$row['id']} LIMIT 1");
}



