确定 Google 地图 API 是否在运行时使用了无效密钥

Determine if Google Maps API is using an invalid key during runtime

我正在寻找一种方法来确定是否使用了有效的 Google 映射 API 密钥。使用无效密钥时,我们会收到一条错误消息,指出 google API 已被禁用。我想捕获 return,并确定是否根据 return 执行我们的地理编码功能。

就目前而言,当我们保存记录时,我们会查看地址是否已更改。如果有,我们获取该地址的地理编码,在 success/failure 消息传回后,我们在保存记录之前继续我们的处理。

当 API 被禁用时,代码就停止了。什么都没有 returned - 没有成功或失败。在这一点上,我们的代码停止以及我们依赖 return 所以我们知道从那里去哪里。我们不是在寻找一种绕过许可的方法,只是一种确定 API 是否在运行时被禁用的方法。有什么想法吗?

遗憾的是,没有实现选项来检测禁用 API。

去年我做了一个 feature-request ,但我不认为会有什么事情发生。

两个可能的选项(可能还有更多):

  1. 当你使用地图时,通常 API 首先会尝试创建地图(一些元素会被添加到地图容器中)。当 API 被禁用时,这些元素将被删除。所以当这种情况发生时你可以做一些事情(例如设置一个指示禁用状态的变量):

     document.getElementById('map-canvas')//map-container
      .addEventListener ('DOMNodeRemoved', function(e){
          if(!this.children.length){
            alert('the API has been disabled');
            if(window.google && window.google.maps){
              window.google.maps.disabled=true;
            }
          }
        }, false);
    
  2. 覆盖 alert 方法以拦截特定消息:

    (function(f){
      window.alert=function(s){
        if(s.indexOf('Google has disabled use of the Maps API for this application.')
           ===0){
    
          if(window.google && window.google.maps){
            window.google.maps.disabled=true;
            alert('the API has been disabled');
            return;
          }
        }
        f(s);
      }
    })(window.alert)
    

在这两种情况下,您稍后可以使用 google.maps 的(自定义)disabled-属性 来检查 API 是否已被禁用:

if(google.maps.disabled===true){
  //execute alternative code
}

嗯,我在 Web > Maps JavaScript API > Events 的标题 "Listening for authentication errors"

中找到了一些内容

If you want to programmatically detect an authentication failure (for example to automatically send an beacon) you can prepare a callback function. If the following global function is defined it will be called when the authentication fails.

所以你只需要定义一个全局函数:

function gm_authFailure() { /* Code */ };