Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 447
Christian Studer Avatar asked Jun 10 '09 09:06

Christian Studer


People also ask

How do I change my Google Maps API key?

Go to the Google Maps Platform > Credentials page. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. Click Close.

Can Google Maps API key be used in multiple domains?

When you create a Google Maps API key, it can be locked to only be used on specific domains that you authorize. These domain names are called "referrers", and your API key won't work on other domains.

Is Google Maps dynamic or static?

The Google Maps Platform static web APIs let you embed a Google Maps image on your web page without requiring JavaScript or any dynamic page loading. The APIs create an image based on URL parameters sent through a standard HTTP request and allow you to display the result on your web page.

Can I use Google Maps API without API key?

Googlemaps API key is required for built-in theme map element as it offers advanced options for map style, zoom and marker. However, you may use a standard Google Maps block of WPBakery or Elementor page builder to set up Google maps without API key.


1 Answers

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

like image 68
Jonathan Fingland Avatar answered Sep 30 '22 03:09

Jonathan Fingland