Fri 20 Mar

jQuery.getScript() and the Google Maps API

I spent a lot of today trying to figure out issues with loading the Google Maps API dynamically. Rather than burden every page in the system with the Google Maps code, I only wanted to load it if there was actually a map on the page.

So I decided to try jQuery’s .getScript() function. Easy enough, right? Wrong.

The first gotcha I ran into was https. We serve a lot of our pages over an SSL connection, so to avoid the insecure content warnings in Internet Explorer, I tried this:

$.getScript("https://maps.google.co.uk/maps?file=api&v=2&key=my_API_key");

This returned the HTML code for the google homepage. Very odd. That one had me wondering for ages, right up until I ranted on twitter. Quick as a flash, googlemapsapi responded:

@OllyHodgson The Google Maps API can only be accessed over SSL for API Premier customers - http://code.google.com/apis/maps/faq.html#ssl

Ah. Revert to http then. And so to the next hurdle:

$.getScript("http://maps.google.co.uk/maps?file=api&v=2&key=my_API_key");

As soon as I called this, my entire page disappeared. Nothing but a blank screen. GAH! Extensive googling only turned up one solution, which didn’t work at all (although it came in handy later on).

A bit of digging revealed a document.write call in Google Maps’ script. The page is already loaded at this point, so it completely overwrites the existing HTML. Brilliant.

Some time later, I stumbled across the async parameter somewhere on google. Adding async=2 to the querystring solved the problem for me:

$.getScript("http://maps.google.co.uk/maps?file=api&v=2&async=2&key=my_API_key");

Finally, I wanted to fire off a function to add the maps to the page, but not until the maps script had loaded completely. I did that using the callback parameter (that overfl0w had suggested earlier):

function placeMap() {
/* Do stuff here */
}
$.getScript("http://maps.google.co.uk/maps?file=api&v=2&async=2&callback=
placeMap&key=my_API_key");

Sorted. All I had to do then was place the maps on the page. I used the excellent jMaps plugin for jQuery (again, loaded using $.getScript()).

I hope that’s useful to someone.