Can I change/set the Google Maps API Key dynamically from JavaScript?

吃可爱长大的小学妹 提交于 2019-12-09 00:13:41

问题


I'm faced with a problem with a small web application I'm developping: My HTML-source will be integrated into the HTML source on another site. I'm using a Google Map in my code, so I have to pass a API-Key for loading the Google Maps-script on the current domain.

The problem: My code will be integrated on two different domains, requiring two different API-Keys. I have those two keys and can identify the valid one by JavaScript (With the help of document.location.host), but how can I manage to dynamically load the script with the correct key?

For reference: The key is passed as parameter in the script loading url:

<script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg" type="text/javascript">
</script>

回答1:


Use

var script = document.createElement("script");
script.setAttribute("src",whatever);
document.getElementsByTagName("head")[0].appendChild(script);

Replace whatever with the script source you want to use




回答2:


I just blogged a would-be solution to this problem. Take a look and let me know what you think. It's a context processor that dynamically loads the key based on the domain in the request.



来源:https://stackoverflow.com/questions/974564/can-i-change-set-the-google-maps-api-key-dynamically-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!