根据缩放级别显示/隐藏标记
我试图根据缩放级别显示/隐藏一些Google地图标记。 我已经在这里看到了答案,虽然我对自己的意图有了更好的理解,但我还没有能够将其实施到Google地图中的运气。
var infowindow = new google.maps.InfoWindow();
var marker, i;
var locations = [
['<div style="width: 170px;">Title1</div>', 50.794785, -1.116947, image],
['<div style="width: 190px;">Title2</div>', 50.797, -1.109, image],
['<div style="width: 120px;">Title3', 50.796928, -1.107119, '../images/map-pointer.png'],
['<div style="width: 150px;">Title4</div>', 50.794703, -1.117880, '../images/map-pointer.png']
];
/* Get the markers from the array */
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,
icon: locations[i][3],
zIndex: 10
});
/* Open marker on mouseover */
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
/* Change markers on zoom */
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom = map.getZoom();
if (zoom <= 15) {
marker.setMap(null);
} else {
marker.setMap(map);
}
});
标记绘制好,但我试图做的缩放功能似乎并没有工作 - 我做错了吗?
您需要将标记保存在数组中,并遍历它们以在缩放事件上显示/隐藏它们。 您只会将最后一个标记保存在marker
变量中。 你需要一个markers
数组。 此外,您可以使用标记的setVisible
方法而不是使用setMap
。
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = [];
var locations = [
['<div style="width: 170px;">Title1</div>', 50.794785, -1.116947, image],
['<div style="width: 190px;">Title2</div>', 50.797, -1.109, image],
['<div style="width: 120px;">Title3', 50.796928, -1.107119, '../images/map-pointer.png'],
['<div style="width: 150px;">Title4</div>', 50.794703, -1.117880, '../images/map-pointer.png']
];
/* Get the markers from the array */
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,
visible: true, // or false. Whatever you need.
icon: locations[i][3],
zIndex: 10
});
/* Open marker on mouseover */
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
markers.push(marker); // save all markers
}
/* Change markers on zoom */
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom = map.getZoom();
// iterate over markers and call setVisible
for (i = 0; i < locations.length; i++) {
markers[i].setVisible(zoom <= 15);
}
});
链接地址: http://www.djcxy.com/p/81585.html