How to check if Google Maps API is loaded?
Solution 1:
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.
Solution 2:
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:
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.
};