Load google maps v3 dynamically with ajax

Found a practical way.

Fiddle here with custom event (jQuery): http://jsfiddle.net/fZqqW/94/

window.gMapsCallback = function(){
    $(window).trigger('gMapsLoaded');
}

$(document).ready((function(){
    function initialize(){
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(47.3239, 5.0428),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    }
    function loadGoogleMaps(){
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type","text/javascript");
        script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    }
    $(window).bind('gMapsLoaded', initialize);
    loadGoogleMaps();
})());​

EDIT
The loadGoogleMaps function might be more practical if declared in the global scope, especially when working in an ajax application. And a boolean check will prevent loading the api multiple times because of navigation.

var gMapsLoaded = false;
window.gMapsCallback = function(){
    gMapsLoaded = true;
    $(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
    if(gMapsLoaded) return window.gMapsCallback();
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

$(document).ready(function(){
    function initialize(){
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(47.3239, 5.0428),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    }
    $(window).bind('gMapsLoaded', initialize);
    window.loadGoogleMaps();
});

Leave a Comment