如何在 html javascript 中验证 google 映射 api 键?
How to verify a google maps api key in html javascript?
我有一个相当标准的 Google 地图页面,使用我自己的 API 键。该页面仅通过 JS 添加一些标记并将其呈现在文本框中。如果密钥无效或过期或其他原因,将显示以下页面。
很好,但是我想至少告诉用户为什么它是错误的。地图访问标准:
...
<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>
...
但是,我想检查 API 密钥是否有效,并在该文本框中告诉用户该密钥是否正常。
我该怎么做?
PS。在 src=
中使用 callback
函数的问题在于它 returns 不管 API 状态是什么,但实际上不是状态本身。 Here 是一个解决方案。
编辑:我在晦涩难懂的 poorly documented 回调函数 gm_authFailure()
中找到了答案,并通过以下方式解决了我的问题:
function gm_authFailure() {
let apiError = "No or invalid API key!"
document.getElementById('status').value = apiError;
};
您甚至不需要在 URL 中指定此回调,它无论如何都会使用它!
添加这个:
function gm_authFailure() { alert('yo'); };
在全局范围内。据此:
https://developers.google.com/maps/documentation/javascript/events#auth-errors
我有一个相当标准的 Google 地图页面,使用我自己的 API 键。该页面仅通过 JS 添加一些标记并将其呈现在文本框中。如果密钥无效或过期或其他原因,将显示以下页面。
很好,但是我想至少告诉用户为什么它是错误的。地图访问标准:
...
<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>
...
但是,我想检查 API 密钥是否有效,并在该文本框中告诉用户该密钥是否正常。
我该怎么做?
PS。在 src=
中使用 callback
函数的问题在于它 returns 不管 API 状态是什么,但实际上不是状态本身。 Here 是一个解决方案。
编辑:我在晦涩难懂的 poorly documented 回调函数 gm_authFailure()
中找到了答案,并通过以下方式解决了我的问题:
function gm_authFailure() {
let apiError = "No or invalid API key!"
document.getElementById('status').value = apiError;
};
您甚至不需要在 URL 中指定此回调,它无论如何都会使用它!
添加这个:
function gm_authFailure() { alert('yo'); };
在全局范围内。据此:
https://developers.google.com/maps/documentation/javascript/events#auth-errors