简体   繁体   中英

Catch Google Maps API errors when using requirejs async plugin

I have a JS app in deployment that depends upon Google Maps. I load the Google Maps SDK for JS using the async plugin for RequireJS...

mapsKey = '&key=' + MY_API_KEY;
mapsURL = 'https://maps.googleapis.com/maps/api/js?libraries=places,geometry&v=3' + mapsKey;
define('GoogleMaps', ['async!' + mapsURL], function() {
    return window.google.maps;
});

I fetch MY_API_KEY from our server as I'd rather not have it in the app code. If our server is temporarily unavailable and the key value cannot be fetched, or for some reason Google rejects the API Key, there is a console error...

"Google Maps API error: Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error"

and worse, an ugly popup in the app...

在此处输入图片说明

I have a valid API Key setup with Google and things work fine. But if there is a loading error, I'd like to retry without an API Key. Google does emit a warning in the JS console about the missing key, but at least for now it still works as a last resort.

QUESTION: How does one catch Google Maps API errors?

The error is thrown from within the Google Maps library during the loading process. This is not a timeout, but an invalid key parameter error. Checking the resulting window.google.maps instance is not an option, as the ugly popup message is already displayed. I do not see a way to trap the error and prevent the popup. I'd like to provide some defensive code to retry without an API Key as a last resort.

You can catch authentication errors with this global function:

function gm_authFailure() { /* Code */ };

If you want to programmatically detect an authentication failure (for example to automatically send an beacon) you can prepare a callback function. If the following global function is defined it will be called when the authentication fails. function gm_authFailure() { /* Code */ };

https://developers.google.com/maps/documentation/javascript/events#auth-errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM