Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load google maps v3 dynamically with ajax

When i try to load google maps v3 with ajax the result is:

<script src="http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/8a/main.js" type="text/javascript"></script>

in the source code, i suppose that writes with javascript document.write();

how i can do this without iframe?

thanks.

like image 892
ZiTAL Avatar asked Oct 13 '10 10:10

ZiTAL


2 Answers

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();
});
like image 54
Armel Larcier Avatar answered Nov 16 '22 21:11

Armel Larcier


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

like image 23
Chris Broadfoot Avatar answered Nov 16 '22 19:11

Chris Broadfoot