开发者

How do I catch an invalid API key for google maps

I have this code:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=babab" type='text/javascr开发者_运维知识库ipt'></script> 

If the key is invalid then it pops up an alert, but I want to perform some action in this case. I'm not sure how to hook into it though. Any ideas?


Google does not offer an external method of checking the Google Maps API key. Hence you cannot query some service with e.g. "Is this code valid abcde1234" and get a TRUE/FALSE response.

There is a discussion on how the Maps API key is generated. But I suggest you look at a post from Mike Williams about the GValidateKey function. This is the function actually doing the magic validation - what it exactly does, like creating a hash from your Google account / domain - we don't know.

I see two solutions for your problem of checking whether the API key provided is correct:

  1. Overwrite the incoming alert with some custom code (check for the content of the alert, or check if an alert occurs withing X seconds after page load)
  2. Somehow get the GValidateKey function to validate your key beforehand. Maybe you can call it before referencing the API Javascript? Sounds kind of hackish to me...

The problem you will likely have is that you don't know what Google actually checks. The referrer, the referring site, the host - many possibilities (it is not the IP address of the server, but the name plus some additional information).


I just ran across the need to perform an action if an invalid API key was used. Google's documentation states:

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.

This was all I needed to do:

function gm_authFailure() { // Perform action(s) }


For modern browsers (IE9+ and others) you may use DOMNodeRemoved event. You just need to add event handler to the element that you pass to the map constructor:

var map = new google.maps.Map(element, myOptions);

 element.addEventListener("DOMNodeRemoved", function(e){
   if (e.target === element){
     //your code here
     element.removeEventListener("DOMNodeRemoved", mapWasRemovedHandler, true);
   }
 }, false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜