Search code examples
javascriptgoogle-mapsapi-key

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


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>

Solution

  • 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