How to load google maps libraries dynamically

倾然丶 夕夏残阳落幕 提交于 2020-01-14 02:23:05

问题


I know I can load libraries in google maps api v3 using libraries argument in URL. Now I am in the situation where I cannot change the html markup, only javascript. Can google maps libraries be loaded dynamically using some javascript call, e.g. by calling some google api function? E.g. something like google.load().


回答1:


I know this question is rather old, but I had the same problem recently. In my case I couldn't easily change the script-load-url but attach js-code afterwards. Double loading google-maps-js couldn't solve the problem as well beecause it is prohibited by google.

To use libraries I copied the code blocks I needed from the respective urls. For loading places it has looked like:

goto: https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&language=de&libraries=places

and copy'paste the last block which looks like:

google.maps.__gjsload__('places', function(_){ ... })

include it in your script after loading the default api.

Remember: This is rather dirty but could solve problems for some of you. Cheers!




回答2:


Google maps documentation show a way to asynchronously load the API

Code from that page:

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src="http://maps.googleapis.com/maps/api/jskey=API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
  document.body.appendChild(script);
}
window.onload = loadScript;


来源:https://stackoverflow.com/questions/17621756/how-to-load-google-maps-libraries-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!