如何在HTML JavaScript中验证Google Maps API密钥? [英] How to verify a google maps api key in html javascript?

查看:141
本文介绍了如何在HTML JavaScript中验证Google Maps API密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标准的Google Maps页面,使用我自己的API密钥.该页面仅通过JS进行一些标记添加,并将其显示在文本框中.如果密钥无效,过期或其他原因,则显示以下页面.

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>
...

但是,我想检查该API密钥是否有效并且有效,并在该文本框中告诉用户该密钥是否正确.

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.

我该怎么办?

PS.在src=中使用callback函数的问题是,无论API状态是什么,它都会返回,但实际上不是状态本身. 在这里是对此的一个无奈的解决方案.

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.

编辑:我在一个晦涩难懂的记录不充分的回调函数gm_authFailure(),并通过以下方式解决了我的问题:

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; 
};

您甚至不需要在URL中指定此回调,它仍然会使用它!

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

推荐答案

添加此内容:

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

在全球范围内.按照这个:

In the global scope. Per this:

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

这篇关于如何在HTML JavaScript中验证Google Maps API密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆