Home > Software > Hacking Google Maps Geocoding

Hacking Google Maps Geocoding

October 26th, 2005

Tonight I was experimenting with google maps and geocoding. It turns out it’s not too difficult to extract geocoordinates from google maps. Basically, the key is to add the extra query parameter ouput=js

Once you do that google outputs the response as javascript with a nice xml document embedded within. Using a few regular expressions to extract the xml and we have some very sophisticated results from our friends google.

The following is a very simple example, in php that searches for a location near DC. What someone might want to do with this little trickier and googles nice javascript api is beyond me ;-)

header('Content-Type: text/xml');

$address = strip_tags($_GET["address"]);
$query = 'http://maps.google.com/maps?q=' .
urlencode( $address ) .
'&sll=38.880660,-77.114642&sspn=0.023753,0.039439&hl=en' . // near DC
'&output=js';

$gm = fopen( $query, 'r' );
if( !$gm ){
return;
}
$buffer = "";
while( !feof( $gm ) ){
$buffer .= fgets($gm, 4096);
}
fclose($gm);

// correct end tags
// "/\\\//\//g"
$buffer = preg_replace( "/<\/\\//", "";
$locs = $doc->getElementsByTagName( "locations" );
echo $doc->saveXML($locs->item(0)) . "\n";

Update

This no longer works.  Google started returning JSON.  Also, google now has GeoCoding built in to their API.

Software , , ,

  1. Anonymous
    November 16th, 2005 at 22:05 | #1

    What does this do? I don’t get it.

  2. todd
    November 16th, 2005 at 23:19 | #2

    it lets you get back either a welformed xml response that is easily parsable of the exact address, or a suggestion from google about what address you may have meant with their locations.

  3. Anonymous
    June 29th, 2007 at 06:27 | #3

    (I hope Horde …)
    But did your code still work?
    I’m having some trouble making it work with the actual gmaps api.
    the output=js still work but I get this responce
    XML: non well-formed

    can you help?

  4. taf2
    July 6th, 2007 at 13:55 | #4

    In reply to anonymous, yeah the above won’t work anymore as it is because, google now responds with JSON. This is actually much nicer because it means from the client you can easily access any of the fields.

  1. No trackbacks yet.
CommentLuv Enabled

Comments links could be nofollow free.