Google Static Maps and localhost

Google Maps has a non-JavaScript mapping feature called Google Static Maps that generates a static map on the server, based on parameters you provide on the URL. The static maps are just a single GIF. You can’t zoom or pan them, but you can specify the location, zoom level and even markers. It’s handy for when you don’t want the overhead of the DHTML maps. You specify all the parameters for your map on the query string, and then set that as the src of an HTML <img> tag.

Here’s what the query string looks like:

http://maps.google.com/staticmap?center=37.763761,-122.396102&markers=37.763761,-122.396102,red&zoom=13&size=400x300&key=ABQIAAAAN0JyO4tW04-1OKNW7bg9gxSPySWqAfkZkuZG2U8jr6yyIuV3XBSrEn410_O9d9QPJh3dbWV85Qad8w

… and here’s what the resulting map looks like (when attached to an HTML <img> tag):

Just like with the JavaScript Google Maps, you need to sign up for a free key. In the static maps, the only place you use the key is in the URL for the map (see above – it’s the last, long parameter on the querystring).

I ran into a slightly confusing issue while using this today. The symptoms were that while developing a site on localhost, the static images weren’t appearing when embedded in an <img> tag in an HTML page. However when I copied and pasted the entire URL into my browser directly, the map appeared fine. Using a tool like Fiddler or LiveHTTPHeaders showed that the response was actually:

HTTP/1.x 400 Bad Request

(Note that if you use Fiddler, you can actually see the body of the request too, but it’s not helpful).

The problem turned out to be that when you embed an <img> tag in an HTML page, the browser automatically sends a Referer header when it requests the images src. If you’re developing on localhost, then the URL will include localhost as the domain. It appears that the Google Static Maps service throws an error when the Referer doesn’t match the domain that is specified in the key (which you included in the URL). This is a little confusing, because the regular (JavaScript) Google Maps allows you to use any key when you’re hosting your site off localhost.

The only fix for this is to generate a Google Maps key for localhost (which you can do), and use that for development. Or you can ignore the problem, since it’ll go away as soon as you deploy.

Leave a Reply

Your email address will not be published. Required fields are marked *