How to check if Google Maps API is loaded?

前端 未结 10 2137
花落未央
花落未央 2020-12-04 16:12

How to check if Google Maps API (v3) is loaded?

I do not want to execute mapping scripts if the API did not load due to internet connectivity problems (web page is h

相关标签:
10条回答
  • 2020-12-04 17:04

    If you are using jQuery, I have good news for you:

    if (typeof google === 'object' && typeof google.maps === 'object') {
         gmapInit();
    } else {
         $.getScript('https://maps.googleapis.com/maps/api/js?key='+gApiKey+'&language=en', function(){
             gmapInit();
         });
     }
    

    it's similar to answer-17702802

    0 讨论(0)
  • 2020-12-04 17:09

    if (google.maps) {...} will give you a reference error if google is undefined (i.e. if the API didn't load).

    Instead, use if (typeof google === 'object' && typeof google.maps === 'object') {...} to check if it loaded successfully.

    0 讨论(0)
  • 2020-12-04 17:09

    A simple if(google && google.maps) check didn't work for me; I still get an error when I try to access the API:

    TypeError: google.maps.LatLng is not a constructor

    In my case this is probably due to my mouse event handlers being triggered before the maps API has even finished downloading. In this case, to reliably check if maps is loaded, I create a "gmaps" alias and initialise it on dom ready (using JQuery):

    var gmaps;
    $(function () {
        gmaps = google.maps;
    });
    

    then in my event handlers I can simply use:

    if(gmaps) {
        // do stuff with maps
    }
    
    0 讨论(0)
  • 2020-12-04 17:10

    Just so you know, there's an issue with the accepted answer. It will return true if the script has loaded otherwise 'typeof google' may return undefined and throw an error. The solution to this is:

    if ('google' in window && typeof google === 'object' && typeof google.maps === 'object') {...}

    This makes sure a boolean value is always returned.

    0 讨论(0)
提交回复
热议问题