google-mapsgoogle-maps-api-3google-loader

Google Maps API Async Loading


I am loading the Google Maps API script Asynchronously in IE9 using the following code:

function initialize() {
  ...
}

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
  document.body.appendChild(script);
}

window.onload = loadScript;

Now the thing is that when the script is fully loaded the initialize() function is called automatically. But when sometimes the user quota has been exceeded the initialize() function is not called and instead of map we see the plain white screen.

I want to detect this and fire my custom function which displays some alert like: "Error!".

Can anyone tell me to how to do this?

Thanks in advance...


Solution

  • As Andrew mentioned, there isn't a direct way to handle this. However, you can at least account for the possibility.

    Set a timeout for a reasonable time frame (5 secondes?). In the timeout callback function, test for the existence of google and/or google.maps. If it doesn't exist, assume the script load failed.

    setTimeout(function() {
      if(!window.google || !window.google.maps) {
        //handle script not loaded
      }
    }), 5000);
    // Maps api asynchronous load code here.