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( "/<\/\\//", "", $buffer );
// extract the xml, removing all html and most of the javascript
preg_match("/var vpage = '*.*';/", $buffer, $matches );
if( count($matches) == 0 )
return;
$buffer = $matches[0];
// strip out the remaining javascript
$buffer = preg_replace( "/var vpage = '/", "", $buffer );
$buffer = preg_replace( "/';/", "", $buffer );
// load the xml into a dom tree
$doc = DOMDocument::loadXML( $buffer );
// extract what we want from the xml
echo "";
$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.

What does this do? I don’t get it.
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.
(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?
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.