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

偶尔善良 提交于 2020-01-15 01:42:42

问题


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.

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!


回答1:


Add this:

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

In the global scope. Per this:

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



来源:https://stackoverflow.com/questions/49100807/how-to-verify-a-google-maps-api-key-in-html-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!