code etc.

Google Maps Autoloader

A recent project required an arbitrary number of dynamic Google maps embedded on various pages throughout the site. I needed to create a single script that would handle loading the maps wherever HTML containers appeared on the page.

The basic idea is to include the maps script, have an HTML container on the page (#map_canvas), write a JavaScript function to configure and create the map, and then trigger the function.

A combination of jQuery and HTML5′s support for custom data attribute makes generalizing those steps simple.

The solution I wound up used a class (.gmap_container) to mark where the maps needed to appear on the page. All of the necessary information (latitude, longitute, labels for the marker, etc.) were added to the container div as data attributes. jQuery is used to iterate through all the .gmap_container divs, gather the information, and create the Google maps objects after the site has loaded.

jQuery(document).ready(function(){varcount=0;jQuery('.gmap_container').each(function(){varlatitude=jQuery(this).data('lat');varlongitude=jQuery(this).data('long');varlabel=jQuery(this).data('label');varzoom=jQuery(this).data('zoom');varid='gmap_'+count;jQuery(this).attr('id',id);// set up the optionsvarmapOptions={center:newgoogle.maps.LatLng(latitude,longitude),zoom:zoom,mapTypeId:google.maps.MapTypeId.ROADMAP};// create the map objectvarmap=newgoogle.maps.Map(document.getElementById(id),mapOptions);// add a marker to the map objectvarmarker=newgoogle.maps.Marker({position:myLatlng,map:map,title:label});count++;});});

The project has some extra infrastructure: the containers are generated programmatically, using information entered into a database. The JavaScript is only included if the containers are present, and so on. But this basic approach allows for a simple, relatively efficient method of having an arbitrary number of unique maps on a single page.

Remember to limit when and where scripts are loaded on your site. Scripts can be dynamically added to pages using jQuery’s built-in getScript method:

The same effect can be achieved using pure JS (this example is lifted direclty from the documentation):

functionloadScript(){varscript=document.createElement("script");script.type="text/javascript";// remember to add the callback parameter to the JavaScript URLscript.src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";document.body.appendChild(script);}window.onload=loadScript;