javascript - 如何在不在html上添加脚本标签的情况下使用google-maps-api-v3

标签 javascript google-maps-api-3 gulp frontend bower

我已经使用 bower、gulp 和 browserify 自动化了前端开发。我正在使用一个名为 Gmaps 的库处理对谷歌地图的 api 调用。问题是我必须在导入 gmaps 之前在我的 html 上添加一个脚本标签。

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true"></script>  

我尝试从脚本链接下载 js 代码并连接到我的其他 js 文件,但没有成功,希望创建一个 all.min.js 并避免在我的网站上有多个脚本标签。

我只能设法将脚本标签添加到 html 来完成这项工作。是否有在串联文件中使用 google maps api 的方法?

最佳答案

当您想使用 maps-API 而无需另外 <script> 时-文档中的元素答案很明确: maps-API 不仅使用了 1 个脚本,它还会向文档中注入(inject)更多脚本。

但是当问题与您必须“手动”包含的脚本数量有关时,答案是肯定的。

可以通过回调异步加载 maps-API,工作流程为:

  1. load the maps-API asynchronously
  2. 创建一个函数(您在步骤#1 中定义为回调的函数)
  3. 回调内部:
    1. 初始化 GMap
    2. 运行通过 GMaps 创建 map 的指令

window.addEventListener('load',function(){

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3&callback=initGmaps';
  document.body.appendChild(script);
});


function initGmaps(){
   //paste here the contents of gmaps.js
   //........

   //then use GMaps
   new GMaps({
        div: '#map',
        lat: 0,
        lng: 0,
        zoom:1
       });
}

演示:http://jsfiddle.net/doktormolle/cr1w32qn/

关于javascript - 如何在不在html上添加脚本标签的情况下使用google-maps-api-v3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490425/

相关文章:

javascript - 解析创建用户示例不起作用

php - 可以根据复选按钮实时向 html 代码添加文本吗?

javascript - 如何知道街景全景图是在室内还是室外

javascript - 如何以编程方式循环遍历文件并要求每个文件?

node.js - 错误: Invalid or corrupt jarfile while giving webdriver-manager start

javascript - AngularJS 中 "trusted html"的意义是什么

javascript - 无效管道参数 : 'Unable to convert "2018-01-01-12:12:12:12345 6"into a date' for pipe 'DatePipe'

javascript - 谷歌地图 api 标记不显示

html - 从谷歌地图和 HTML 5 GeoLocation 获取国家代码

javascript - 为什么需要browserify `paths`定义?