19Mar/130

Dynamicly load Google Maps v3

Quite often pages are overloaded with 3rd party APIs or widgets and page loading time becomes a bottleneck in user experience. In my project I need google maps support, but only if user selects one particular tab.

So how to load Google Maps V3 dynamicly, on button click or tab select

Main steps here are load maps API, wait for load, create map and wait for tiles to load.

Load maps API

First step is to load javascript API. One important thing here is callback parameter. That function will be executed after API is fully loaded.

$.ajax({
   url: "http://maps.googleapis.com/maps/api/js?sensor=false&callback=MapApiLoaded",
   dataType: "script",
   timeout:8000,
   error: function() {
      // Handle error here
   }
});

Create map object and wait for full load

Next, define function MapApiLoaded, good place to create map object and setup.

function MapApiLoaded() {
   // Create google map
   map = new google.maps.Map($('#gmap')[0], {
      zoom:8,
      mapTypeId:google.maps.MapTypeId.ROADMAP,
      panControl:false,
      streetViewControl:false,
      mapTypeControl:true
   });
   map.setCenter(new google.maps.LatLng(-1.950106, 29.873887999999965));
 
   // Add marker
 
   // Trigger resize to correctly display the map
   google.maps.event.trigger(map, "resize");
 
   // Map loaded trigger
   google.maps.event.addListenerOnce(map, 'idle', function () {
      // Fire when map tiles are completly loaded
   });
}
Did you find this post useful? Support the the author ($10)
My Google Profile+
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.