最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - dynamically set googleapi key - Stack Overflow

programmeradmin2浏览0评论

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="="+GOOGLE_MAP_KEY+"&sensor=true">
</script>

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

Request URL:  =

the rest of the URL is lost.

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

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?

Share Improve this question edited Jul 10, 2015 at 13:51 duncan 31.9k15 gold badges81 silver badges101 bronze badges asked Jul 10, 2015 at 13:44 user2777473user2777473 3,8267 gold badges28 silver badges41 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 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>

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.

You would have to load your Script dynamically.

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

发布评论

评论列表(0)

  1. 暂无评论