Load google maps v3 dynamically with ajax

Solution 1:

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();
});

Solution 2:

This is not supported. Please load the API using supported methods:

http://code.google.com/apis/maps/documentation/javascript/tutorial.html#Loading_the_Maps_API

Solution 3:

I've done it like so... this example uses jQuery and google map v3.x

$.getScript("http://maps.google.com/maps/api/js?sensor=true&region=nz&async=2&callback=MapApiLoaded", function () {});

function MapApiLoaded() {
   //.... put your map setup code here: new google.maps.Map(...) etc
}

Solution 4:

You must use this parameter 'callback=initialize' in the google maps API script to load with ajax:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>

Here is a google maps documentation:

Cómo cargar el API de forma asíncrona