Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically set googleapi key

I have a application wants to embed google map, and it is required that the key is put into a config file. So here is what I do:

In config.js

GOOGLE_MAP_KEY = "mykeyofgoogleapi";

In index.html

<script type="text/javascript" 
        src="https://maps.googleapis.com/maps/api/js?key="+GOOGLE_MAP_KEY+"&sensor=true">
</script>

The problem is that I see the GET URL to google is only

Request URL:  https://maps.googleapis.com/maps/api/js?key=

the rest of the URL is lost.

Looks I did something bad in concat the URL like this. What is wrong?

like image 649
user2777473 Avatar asked Jul 10 '15 13:07

user2777473


People also ask

Is it OK to expose Google API key?

If you're building a GCP application, see using API keys for GCP. When you use API keys in your Google Cloud Platform (GCP) applications, take care to keep them secure. Publicly exposing your credentials can result in your account being compromised, which could lead to unexpected charges on your account.

Can I get Google API key free?

Once you have an account and a free Google Maps API key, you can start working with the API directly. The key is a unique identifier that authenticates requests for your application.

How do I get a static API key for Google Maps?

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.


1 Answers

Where you're specifying the <script> tag, you're writing HTML not Javascript (even though you're using it to load in a JS file). So you can't reference Javascript variables in the HTML.

Instead to do this you need to load the Google Maps JS using javascript, not HTML. See for instance the example they have in the docs: https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

<script>
var GOOGLE_MAP_KEY = "mykeyofgoogleapi";

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3' +
      '&key=' + GOOGLE_MAP_KEY +'&callback=initialize'; //& needed
  document.body.appendChild(script);
}

window.onload = loadScript;
</script>
like image 153
duncan Avatar answered Sep 21 '22 06:09

duncan