Jeremiah Sturgill

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 Google maps API documentation introductory code looks like this:

<!-- snip -->
    <!-- include the Google maps JavaScript -->
    <script type="text/javascript"  
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE"> 
    </script> 

    <!-- create a function that loads a single map -->
    <script type="text/javascript"> 
      function initialize() { 
        var mapOptions = { 
          center: new google.maps.LatLng(-34.397, 150.644), 
          zoom: 8, 
          mapTypeId: google.maps.MapTypeId.ROADMAP 
        }; 
        var map = new google.maps.Map(document.getElementById("map_canvas"), 
            mapOptions); 
      } 
    </script> 
  </head> 
  <!-- call the map function once the body is fully loaded -->
  <body onload="initialize()"> 
    <div id="map_canvas" style="width:100%; height:100%"></div>
<!-- snip -->

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(){
  var count = 0;
  jQuery( '.gmap_container' ).each( function(){
    var latitude = jQuery( this ).data( 'lat' );
    var longitude = jQuery( this ).data( 'long' );
    var label = jQuery( this ).data( 'label' );
    var zoom = jQuery( this).data( 'zoom' );
    var id = 'gmap_' + count;
    jQuery( this ).attr( 'id', id );

    // set up the options
    var mapOptions = { 
        center: new google.maps.LatLng( latitude, longitude ), 
        zoom: zoom, 
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // create the map object
    var map = new google.maps.Map(document.getElementById( id ), mapOptions);

    // add a marker to the map object
    var marker = new google.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:

// remember to add the callback parameter to the JavaScript URL
jQuery.getScript( 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE&callback=initialize', function(){
    // maps js here
});

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

function loadScript() {
    var script = document.createElement( "script" );
    script.type = "text/javascript";
    // remember to add the callback parameter to the JavaScript URL
    script.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;