谷歌地图API在链接功能中的按钮点击时未加载



基本上,我有一个谷歌地图API,作为一个从一个函数到另一个函数的链式调用加载。我可以让它完美地工作,如这个 JsFiddle 所示,但由于某种原因,当它来自带有一点额外 HTML 的链式调用时,它不会将实际的 Map 加载到目标div中。这是不工作的 JsFiddle,但更能代表我的生产代码:https://jsfiddle.net/NateH06/twk9mtjg/2/.控制台打印输出指示所有映射绑定已成功发生,但它不会显示在目标div.gmap中。

这是我的 HTML:

<div style="display: none;" class="googleMapsContainer" id="gm2">
This Text Should be visible after click
<div class="gmap" id="map">
<!--Map should load here on button click -->
</div>
</div>
<br>
<div class="tableProcessingToolBarContainer">
<div class="container-fluid tableProcessingTools">
<div class="row-fluid">
<div class="appSliderContent tptSliderContent container-fluid ">
<button class="gmapInit glassyButton">View data in Google Maps</button>
</div>
</div>
</div>
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDYpu-wE1AEWVUzEUq7RXOhX_3dQUJ2RUw">
</script>

这是Javascript,它都很好:

$(document).on('click', '.gmapInit', function() {
var mapContainer = $(this).parents("div.tableProcessingToolBarContainer").prevAll("div.googleMapsContainer:first");
mapContainer.attr("style", "");
var mapTarget = mapContainer.children(".gmap");
initMap(mapTarget);
});
function initMap(targetElem) {
console.log("this fires, here's target elem: ");
console.log(targetElem);
var uluru = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(targetElem, {
zoom: 4,
center: uluru
});
console.log(map);
var marker = new google.maps.Marker({
position: uluru,
map: map
});
console.log(marker);
}

注意在jsfiddle 中你是这条线

console.log(targetElem);

显示为

[div#map.gmap]

在控制台中?

这是因为你的 targetElem 变量实际上是元素的集合,这就是 jQuery 选择器返回的(jQuery 对象(。 google.maps.Map 构造函数在构造函数中采用单个元素。 所以你可以做 targetElem[0] 来获取集合中的第一个元素,这是你在这种情况下真正想要的。 但是,我建议重组选择该元素的方式,因为遵循选择器链有点困难。 有什么理由你不能只做:

$(document).on('click', '.gmapInit', function() {
var mapTarget = document.getElementById("map");
initMap(mapTarget);
});

最新更新