我可以从 JavaScript 动态更改/设置 Google Maps API 密钥吗?
我正在开发的一个小型 Web 应用程序遇到一个问题:我的 HTML 源代码将被集成到另一个站点上的 HTML 源代码中.我在代码中使用了 Google 地图,因此我必须传递一个 API-Key 以在当前域上加载 Google 地图脚本.
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.
问题:我的代码将集成到两个不同的域中,需要两个不同的 API 密钥.我有这两个键并且可以通过 JavaScript 识别有效的一个(在 document.location.host 的帮助下),但是我如何设法使用正确的键动态加载脚本?
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?
供参考:key在脚本加载url中作为参数传递:
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>
使用
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