Trovato un modo pratico.
Fiddle qui con l'evento personalizzato (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 La funzione loadGoogleMaps
potrebbe essere più pratico se dichiarato nella portata globale, soprattutto quando si lavora in un'applicazione Ajax. E un controllo booleano impedirà di caricare l'API più volte a causa della navigazione.
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();
});
fonte
2012-09-26 13:27:07
Ho modificato il codice e aggiunto codice di esempio. Per favore ricontrolla. –
cosa succede se non ne hai più bisogno in una SPA più tardi? Perché l'utente deve aspettare che lo script venga caricato? – SuperUberDuper