Can I change / set the Google Maps API key dynamically with JavaScript?

I have a problem with a small web application that I am developing: my HTML source will be integrated into the HTML source on another site. I use a Google map in my code, so I need to pass an API key to load the Google Maps script in the current domain.

Problem: my code will be integrated into two different domains requiring two different API keys. I have these two keys and I can determine the valid one using JavaScript (using document.location.host), but how can I control the dynamic loading of the script using the correct key?

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

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

Use

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

Replace the source of the script you want to use

+5
source

I just posted a potential solution to this problem on my blog . Take a look and let me know what you think. This is a context processor that dynamically loads a domain-based key in a request.

0
source

Source: https://habr.com/ru/post/1710136/


All Articles