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.
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();
});
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
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®ion=nz&async=2&callback=MapApiLoaded", function () {});
function MapApiLoaded() {
//.... put your map setup code here: new google.maps.Map(...) etc
}
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:
Simple and working solution (using jQuery):
var gMapsLoaded = false;
function loadGoogleMaps() { if(!gMapsLoaded) { $.getScript("https://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=GoogleMapsLoaded", function(){}); } else { GoogleMapsLoaded(); } }
function GoogleMapsLoaded() {
gMapsLoaded = true;
// your code here - init map ...
}
paste this in your scripts and then call function loadGoogleMaps(); when you need it!
I’ve changed a little bit Myster sample, that looks working well for me
window.mapapiloaded = function () {
console.log('$.ajax done: use google.maps');
createusinggmaps();
};
$.ajax({
url: 'http://maps.google.com/-maps/api/js?v=3.2&sensor=true®ion=it&async=2&callback=mapapiloaded',
dataType: 'script',
timeout: 30000,
success: function () {
console.log('$.ajax progress: waiting for mapapiloaded callback');
},
error: function () {
console.log('$.ajax fail: use osm instead of google.maps');
createusingosm();
}
});
$LAB
.setOptions({AlwaysPreserveOrder:true})
.script("http://maps.google.com/maps/api/js?v=3.exp&sensor=false&async=2")
.script("http://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/6/main.js")
.script("script.js");
Inside of script.js initialize your map without googles load method for example:
Namespace.map = (function(){
var map,
markers = [];
return{
init: function(){
var myLatlng = new google.maps.LatLng(-25.363882,131.044922),
mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
markers.push(marker);
}
};
}());
Inside of script.js:
Namespace.map.init();
// Don't use: google.maps.event.addDomListener(window, 'load', initialize);
Note: Do not rely on this method as Google changes the name of the second js file. Here is an example from their documentation:
https://developers.google.com/maps/documentation/javascript/examples/map-simple-async
It is now possible. See here
On that page there is also a variant for manual loading, without library.
npm install @googlemaps/js-api-loader
import { Loader } from "@googlemaps/js-api-loader"
const loader = new Loader({
apiKey: "YOUR_API_KEY",
version: "weekly",
...additionalOptions,
});
loader.load().then(() => {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
});