我可以从 JavaScript 动态更改/设置 Google Maps API 密钥吗? [英] Can I change/set the Google Maps API Key dynamically from JavaScript?

查看:39
本文介绍了我可以从 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

这篇关于我可以从 JavaScript 动态更改/设置 Google Maps API 密钥吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆