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

前端 未结 2 787
粉色の甜心
粉色の甜心 2020-12-22 04:12

I\'m looking for a way to determine whether a valid Google maps API key is being used. Using an invalid key, we receive an error stating that the google API has been disable

2条回答
  •  误落风尘
    2020-12-22 04:41

    Unfortunately there is no implemented option to detect a disabled API.

    Last year I've made a feature-request , but I don't think that something will happen.

    two possible options(there may be more):

    1. when you use a map usually the API first will try to create the map(some elements will be added to the map-container ). When the API will be disabled, these elements will be removed. So you may do something when this happens(e.g. set a variable that indicates the disabled-status):

       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. override the alert-method to intercept the particular message:

      (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)
      

    In both cases you may later use the (custom)disabled-property of google.maps to check if the API has been disabled:

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

提交回复
热议问题