嘿我打开/关闭标记时遇到问题
你知道它为什么只切换一个标记(标记“Freilichtmuseum”)吗?
获得帮助!!
var locations = [
['Sensenwerk', 47.20031715397146, 15.338023278873152, 4],
['Freilichtmuseum', 47.158075170093, 15.315393984492403, 5],
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
function toggleLayer() {
if (marker.getMap() === null) {
marker.setMap(map);
}
else {
marker.setMap(null);
}
}
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
答案 0 :(得分:3)
toggleLayer仅切换当前“标记”。如果您希望它比最后一个更多,则需要保存对需要在数组中切换的所有标记的引用并遍历该数组。
var markers = [];
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
function toggleLayer() {
for (var i=0; i< markers.length; i++){
if (markers[i].getMap() === null) {
markers[i].setMap(map);
}
else {
markers[i].setMap(null);
}
}
}