11

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?

duncan
  • 31,401
  • 13
  • 78
  • 99
user2777473
  • 3,736
  • 5
  • 26
  • 39

3 Answers3

17

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>
duncan
  • 31,401
  • 13
  • 78
  • 99
0

You cannot use the + operator in HTML like that. It is specifically a JavaScript operator. Since HTML does not recognize +, it just terminates the string at key=.

An alternative solution is to use Ajax in JavaScript to import the url.

Please see this documentation for more details: https://api.jquery.com/jquery.getscript/. It will require the use of jQuery.

bcdan
  • 1,438
  • 1
  • 12
  • 25
0

You would have to load your Script dynamically.

You might also consider using the newest version of the Maps API (v3):

Community
  • 1
  • 1
SimonR
  • 95
  • 9