[英]Google Maps infowindow shows same content for each marker
我正在處理涉及Google Maps API和信息窗口的問題。 當我單擊一個標記時,會彈出一個信息窗口,並且我正在嘗試創建它,以便在發生這種情況時,該標記的緯度/經度會顯示在信息窗口中。 緯度/經度在這種情況下存儲在stops數組中:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var marker;
var infowindow; //Global infowindow created
function initialize() {
var latlng = new google.maps.LatLng(37.784, -122.408);
var stops = new Array();
stops = [
new google.maps.LatLng(37.7655, -122.4525899),
new google.maps.LatLng(37.7649999, -122.45656),
new google.maps.LatLng(37.7643, -122.4608199),
];
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(37.7655, -122.4525899)
};
map = new google.maps.Map(document.getElementById("content"),
myOptions);
infowindow = new google.maps.InfoWindow({ //infowindow options set
maxWidth: 355
});
var i = 0;
for (i < 0; i < stops.length; i++) {
marker = new google.maps.Marker({
position:stops[i],
map: map,
title: "Stop Coords: "+ stops[i]
});
var len=stops.length;
popupDirections(marker, len, stops);
}
}
function popupDirections(marker, len,stops) {
//this function created listener listens for click on a marker
google.maps.event.addListener(marker, 'click', function () {
for (var i = 0; i < len; i++)
{ infowindow.setContent("Stop coords: " + stops[i]); } //sets the content of your global infowindow to string "Tests: "
infowindow.open(map, marker); //then opens the infowindow at the marker
});
}
現在,當我將鼠標懸停在每個標記上時,會顯示正確的緯度/經度,但是當我單擊標記並彈出信息窗口時,我會不斷獲得停靠點的緯度/經度[2]。 我不確定是什么問題,我對JS的了解非常有限,很幸運在前面的這篇文章中找到了一個有用的文章,該文章顯示了如何創建信息窗口。
我認為解決問題的最佳方法是為每個標記提供“自定義對象屬性” stopCoords
:
for (i < 0; i < stops.length; i++) {
marker = new google.maps.Marker({
position: stops[i],
map: map,
title: "Stop Coords: " + stops[i],
stopCoords: stops[i]
});
var len = stops.length;
popupDirections(marker, len, stops);
}
然后,在popupDirections
函數中,對其進行引用(使用UPDATE或使用marker.position
代替。但要注意的是,您可以將stopCoords
為所需的任何值)。
for (var i = 0; i < len; i++) {
infowindow.setContent("Stop coords: " + marker.stopCoords);
}
演示 http://jsfiddle.net/yV6xv/580/
我將用一些時髦的詞來解釋為什么您的原始代碼不起作用:與可變范圍和閉包有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.