Search code examples
javascripthtmlgoogle-mapsgoogle-maps-api-3api-key

How to verify a google maps api key in html javascript?


I have a rather standard Google Maps page, using my own API key. The page only does some marker additions by JS and presenting it in a text-box. If the key is invalid or expired or whatever, the following page is displayed.

enter image description here

That is fine, but then I would like to at lest tell the user why it is wrong. The map is accessed by standard:

...
<script type="text/javascript" 
        src="http://maps.google.com/maps/api/js?key=API_KEY"></script>
</head>
<body>
<div id="map"></div> 
<p><input type="text" "readonly" id="status" size=40></p>
...

However, I would like to check that the API key is working and valid, and tell the user if the key is OK or not in that text box.

How can I do that?

PS. The problem with using a callback function in the src=, is that it returns regardless what is the API status, but not actually the status itself. Here is a kludge solution of this.


EDIT: I found an answer in the obscurely and poorly documented callback function, gm_authFailure(), and solved my question with:

function gm_authFailure() { 
    let apiError = "No or invalid API key!"
    document.getElementById('status').value = apiError; 
};

You don't even need to specify this callback in your URL, it will use it anyway!


Solution

  • Add this:

    function gm_authFailure() { alert('yo'); };
    

    In the global scope. Per this:

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