Reputation: 11079
I'm loading Google Maps using this technique with code roughly as follows (using jQuery):
$.ajax({
url: "//maps.googleapis.com/maps/api/js?client=" + GOOGLE_MAPS_CLIENT_ID + "&v=" + GOOGLE_MAPS_API_VERSION + "&sensor=false&libraries=geometry&callback=googleMapsOnLoad",
crossdomain: true,
dataType: 'script'
});
where window.googleMapsOnLoad
is my handler for a successful load.
And it works fine generally but there are times where for some of my users, as best I can tell, it just doesn't load properly. Is there some way to attach an error callback that will fire if the load fails in some way?
Upvotes: 0
Views: 1090
Reputation: 146219
You may try something like this, (Demo):
function initialize()
{
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
For cross domain script tag the error
event does not fire, so window.setTimeout
is used:
$(function(){
var timeoutId;
timeoutId = window.setTimeout(function() {
alert("Script Error!");
}, 2000);
var url = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize';
$.getScript(url, function(){ window.clearTimeout(timeoutId) });
});
Upvotes: 1
Reputation: 8077
There's no real way to check, because sometimes it could take a long time for some resources to load (processor, connection speed, etc..). A way to handle this is by setting a proper timeout at a finite time (the following suggest 5 seconds).
function checkGMapsLoad() {
if( !window.googleMapsOnLoad ) {
//Error, Google Maps hasn't loaded yet. Reload page?
//Stuff to perform here
}
}
window.setTimeout( checkGMapsLoad, 5000 );
Edit: Since you're using jQuery to make the call, jQuery.ajax()
has a parameter error
that can be used incase the callback fails.
$.ajax({
url: "//maps.googleapis.com/maps/api/js?client=" + GOOGLE_MAPS_CLIENT_ID + "&v=" + GOOGLE_MAPS_API_VERSION + "&sensor=false&libraries=geometry&callback=googleMapsOnLoad",
crossdomain: true,
dataType: 'script',
timeout: 5000, // <------ Optional
error: checkGMapsLoad // <------
});
Upvotes: 1