67

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 hosted locally).

user1251007
  • 15,891
  • 14
  • 50
  • 76
Nirmal
  • 9,391
  • 11
  • 57
  • 81

10 Answers10

130

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.

DaveS
  • 3,156
  • 1
  • 21
  • 31
  • Thank you, this is what I have been looking for. – Nirmal Feb 11 '12 at 01:11
  • 5
    I'm in a namespaced environment, so simply referencing `google` didn't work for me, I had to use `window.google`. – Jon Jan 04 '14 at 03:08
  • 1
    I believe there are cases were `google.maps` may be defined before the Maps API has entirely finished loading, causing this to break inconsistently. If anyone else has the same issue, may want to try my answer below, using a callback. – Don McCurdy Aug 20 '15 at 18:29
  • It gives me error google is undefined. Why is it that? – Daniela Oct 05 '16 at 18:27
  • Daniela, what's the code you're using to check if google is defined? The typeof operator I suggested shouldn't give a "google is undefined" error. – DaveS Oct 07 '16 at 02:55
30

None of the current answers are working with 100% consistency for me (excluding Google Loader, which I haven't tried). I don't think checking the existence of google.maps is enough to be sure the library has finished loading. Here are the network requests I'm seeing when the Maps API and optional Places library are requested:

maps api network requests

That very first script defines google.maps, but the code that you probably need (google.maps.Map, google.maps.places) won't be around until some of the other scripts have loaded.

It is much safer to define a callback when loading the Maps API. @verti's answer is almost correct, but still relies on checking google.maps unsafely.

Instead, do this:

HTML:

<!-- "async" and "defer" are optional, but help the page load faster. -->
<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=mapsCallback">
</script>

JS:

var isMapsApiLoaded = false;
window.mapsCallback = function () {
  isMapsApiLoaded = true;
  // initialize map, etc.
};
Don McCurdy
  • 10,975
  • 2
  • 37
  • 75
  • 2
    This is a better answer than mine nowadays, if you don't have to support older versions of IE (<9). – DaveS Oct 07 '16 at 03:31
14

in async loading this one works for me (Thanks to DaveS) :

   function appendBootstrap() {
    if (typeof google === 'object' && typeof google.maps === 'object') {
        handleApiReady();
    } else {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=handleApiReady";
        document.body.appendChild(script);
    }
}

function handleApiReady() {
    var myLatlng = new google.maps.LatLng(39.51728, 34.765211);
    var myOptions = {
      zoom: 6,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
ilker
  • 190
  • 5
  • 11
4

You might consider using the Google Loader

google.load("maps", "3", {callback: myFn});

It will load your designated javascript file, then execute the callback, specified in the optionalSettings argument.

Razvan Caliman
  • 4,509
  • 3
  • 21
  • 24
3

EDIT: If you are not afraid to be "not explicit" then you can use following, otherwise if you are not sure if there will be only one instance of google variable then use DaveS answer.

Check if google maps v3 api loaded:

if(google && google.maps){
    console.log('Google maps loaded');
}

in this condition variable google will use javascript truth so if it will be function or object or string it will become true and then will try to access maps inside of that object.

And inverse:

if(!google || !google.maps){
    console.log('Not loaded yet');
}
Ivar
  • 4,350
  • 2
  • 27
  • 29
3

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.

Ric Flair
  • 387
  • 3
  • 5
1

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
}
Nathan
  • 5,272
  • 2
  • 26
  • 28
1

try

(google && 'maps' in google)?true:false

or

if(google && 'maps' in google){
    //true
}
else{
    //false
}

since I had a problem with the following on mobile:

if (typeof google === 'object' && typeof google.maps === 'object') {...}
Nasser Al-Wohaibi
  • 4,562
  • 2
  • 36
  • 28
0

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

Tusko Trush
  • 422
  • 3
  • 15
0

I believe you can do this with an if(google && google.maps){ … }, unless you mean what is in this post, which is about Maps API V2, but someone updated it for v3 here.

Community
  • 1
  • 1
  • `if (google.maps) {...}` threw me an error when the API was not loaded. DaveS has addressed the issue in his answer. Thanks! – Nirmal Feb 11 '12 at 01:16