【问题标题】:Loading Google Maps API with Ajax using Javascript/JQuery, Callback not setup correctly使用 Javascript/JQuery 使用 Ajax 加载 Google Maps API,回调设置不正确
【发布时间】:2013-11-27 22:48:03
【问题描述】:

我希望能提供一些有关使该脚本正常工作的指导。地图加载正常,但回调设置不正确,因此每次单击按钮时页面都会将 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/ 这是我希望通过修改我当前使用的脚本来完成的(而不是反向工程)一个新脚本)。

谢谢。

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

【问题讨论】:

  • 为什么不直接调用函数而不是添加多余的事件和事件监听器?
  • 我不太确定哪些事件是多余的,哪些不是。 ATM 我正在​​扩展我目前对 Javascript 的理解,因为它必须设置回调并使用 AJAX 异步加载内容,所以真的 AFAIK 每个事件都有设置回调的目的。
  • 我现在明白你的评论了。我想额外的脚本对于我的目的来说是多余的。
  • 您可以将其发布为答案,并接受您自己的答案。通常认为它比编辑问题并将答案放在那里更好。

标签: javascript jquery ajax google-maps google-maps-api-3


【解决方案1】:

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

$('.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>

【讨论】:

  • 刚刚对此进行了投票,因为它解决了我遇到的问题。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 2019-07-08
  • 1970-01-01
相关资源
最近更新 更多