我在Google地图标记上的事件侦听器遇到了一个奇怪的问题。基本上,我想在循环中声明一堆标记,并让每个标记都有一个关联的信息窗口。相关代码为:
var markers=[];
var contents = [];
var infowindows = [];
for (i = 0; i < 10; i++) {
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(40+Math.random()*5, 4+Math.random()*5),
map: map,
title: 'samplemarker'
});
contents[i] = '<div class="popup_container">' +
'</div>';
infowindows[i] = new google.maps.InfoWindow({
content: contents[i],
maxWidth: 300
});
google.maps.event.addListener(markers[i], 'click', function() {
infowindows[i].open(map,markers[i]);
map.panTo(markers[i].getPosition());
});
}
标记创建正确,信息窗口也正确创建,因为如果我手动进行操作,infowindows[i].open(map,markers[i]);
它们将正确打开。但是,侦听器不起作用。
甚至更奇怪:我在for循环之外声明了另一个标记“ marker_1”,完全相同。如果我写:
google.maps.event.addListener(marker_1, 'click', function() {
infowindows[0].open(map,markers[0]);
map.panTo(markers[0].getPosition());
});
单击marker_1时,将打开信息窗口0,并将地图平移到标记0。但是,当在完全相同的位置写入相同的行(除了被marker_1替换为marker [0]的marker_1)时,单击标记0完全没有效果。
感谢您的任何帮助,如果这太蠢了,请对不起!
在您的onclick处理程序中,您还没有该i
值,在这种情况下,它将始终取i
循环结束后的最后一个值,即10,并且由于只有10个标记,所以markers [10]不存在。
为了使其工作,您可以例如在数组中的标记中添加其他属性,该属性将存储标记索引并在onlick处理程序中使用它
var markers=[];
var contents = [];
var infowindows = [];
for (i = 0; i < 10; i++) {
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(40+Math.random()*5, 4+Math.random()*5),
map: map,
title: 'samplemarker'
});
markers[i].index = i; //add index property
contents[i] = '<div class="popup_container"></div>';
infowindows[i] = new google.maps.InfoWindow({
content: contents[i],
maxWidth: 300
});
google.maps.event.addListener(markers[i], 'click', function() {
console.log(this.index); // this will give correct index
console.log(i); //this will always give 10 for you
infowindows[this.index].open(map,markers[this.index]);
map.panTo(markers[this.index].getPosition());
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句