Google Maps API 3 - 根据缩放级别显示/隐藏标记

时间:2013-11-18 09:31:32

标签: javascript jquery google-maps google-maps-api-3

我正在尝试显示/隐藏一些谷歌地图标记,具体取决于缩放级别。我已经看过这里的答案了,虽然我已经更好地了解了我的意图,但我没有运气能够将它实现到我的谷歌地图中。

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);
    }
});

标记正在绘制,但我正在尝试的缩放功能似乎根本不起作用 - 我做错了吗?

1 个答案:

答案 0 :(得分:32)

您需要将标记保存在数组中并迭代它们以在缩放事件上显示/隐藏它们。您只保存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);
    }
});