使用 Javascript/JQuery 使用 Ajax 加载 Google Maps API,回调设置不正确

Loading Google Maps API with Ajax using Javascript/JQuery, Callback not setup correctly

本文关键字:使用 API 回调 不正确 设置 Maps Google Javascript JQuery Ajax 加载      更新时间:2023-09-26

我希望得到一些关于让这个脚本工作的指导。地图加载正常,但回调设置不正确,因此每次单击按钮时,页面都会不断将 Google 地图 API 脚本附加到文档中。

我正在使用JQuery的$.load将HTML页面(map.html)添加到DOM元素(div容器)中。

$('.button').click(function() {
        $('#mapcontainer').load('/map.html');
}); 

这是map.html用来加载地图的内容,我使用的脚本起源于这里:https://stackoverflow.com/a/12602845/1607449

<script>
var gMapsLoaded = false;
window.gMapsCallback = function(){
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');}
window.loadGoogleMaps = function(){
if(gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?key=KEYGOESHERE&sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(document).ready(function(){
   function initialize(){
var mapOptions = {
  }
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
$(window).bind('gMapsLoaded', initialize);
window.loadGoogleMaps();
});
</script>
<div style="height:400px;width:650px;" id="map_canvas"></div>

以下是设置回调以动态加载Google Maps Javascript API的另一个不同方法的示例: http://www.vijayjoshi.org/2010/01/19/how-to-dynamically-load-the-google-maps-javascript-api-on-demand-loading/这就是我希望通过修改当前使用的脚本(而不是对新脚本进行反向工程)来实现的。

谢谢。

编辑:解决了问题,解决方案在下面发布回应

想出了一个解决方案,基本上我的回调是不必要的。这是我使用的:

$('.button').click(function() {
        $('#mapcontainer').load('/map.html', function () {
       initialize();
   });
}); 

<script>
function initialize(){
   var mapOptions = {
           ///Map options go here
     }
   };
   map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
</script>
<div style="height:400px;width:650px;" id="map_canvas"></div>