Jan 23

Dynamically Loading Google Maps for Performance

Google, Tech with tags: 8 Comments »

A fellow JavaScripter was running into an issue where the standard way to load the Google Maps API was causing a perceived slow down of a single app page. The API has added the ability to get away from document.write() and dynamically load everything up.

Example code

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.google.com/maps?file=api&v=2.x&key=PUT-YOUR-KEY-HERE&async=2&callback=loadMap";
  document.body.appendChild(script);
}
 
function loadMap() {
  var map = new GMap2(document.getElementById("map"));
  map.setCenter(new GLatLng(37.4419, -122.1419), 6);
  map.addOverlay(new GMarker(map.getCenter()));
}

Here it is at work in an iframe below: