JavaScript Console
Google Maps API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key
According to the Loading the Maps API documentation you have the option to provide a callback function that the Maps API will call once it is loaded...
The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter.
Unfortunately the callback is invoked even when the API key is invalid! A little bit more work is required to make sure that the API key provided works and that the Maps API can be used in the rest of your application. So lets see what's required.
First the callback needs to be set, when loading the Maps API script, I set mine like this...
HTML
https://maps.googleapis.com/maps/api/js?callback=gm_Loaded&libraries=places&key=YOUR_API_KEY
This tells Google Maps API to call a function with the name gm_Loaded when the Maps API has loaded. I then have this block of JavaScript that includes the gm_Loaded() function...
JavaScript
useGmaps = false; /* set to not use by default */
function gm_Loaded() {
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: 'Brisbane,Australia',
types: ['(cities)']
},
function(predictions, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
useGmaps = true; /* status is ok so set flag to use Google Maps */
}
});
};
I set a global variable, useGmaps, to false by default. This variable is used in my application code to check if the Maps API should be used or not. In the gm_Loaded() function, I do a simple call to the AutocompleteService to look up data for a specific city (my home town, but all you need is a location that definitely exists in Google Maps). This call will only succeed if the API key is valid and has access to the Maps API. On a successful call, I make sure that the status is OK and then set useGmaps to true. Unsuccessful calls will never get to the part of the code that sets useGmaps to true.
Now all I do in my application code is a check to make sure that the Maps API should be used, like so...
JavaScript
if (useGmaps === true && typeof(google) !== 'undefined') {
...
}
It's a bit of a hackey approach but it guarantees that any calls to the Maps API will not throw key related exceptions in your code.
-i