我使用以下代码在地图上添加了一些点,它们看起来很棒。我还添加了一些json多边形而没有问题。

当达到某个缩放级别时,我希望关闭点和多边形。使用map.removeLayer(多边形的名称)可以完美地关闭多边形,然后进行缩小,然后使用map.addLayer(多边形的名称),然后它们会回来(使用'zoomend'和if else语句)。

点要素不会像多边形那样对removeLayer函数做出反应。我也尝试了HarvestPoints.setOpacity(0)也不起作用。我应该使用什么代码将这些geojson标记像多边形要素一样“打开”和“关闭”?

function onEachPoint(feature, layer) {
    layer.bindPopup(feature.properties.MGNT_AREA.toString());
    layer.on('click', function (e) { layer.openPopup(); });
    layer.bindLabel(feature.properties.MGNT_AREA.toString(), {
        noHide: true,
        className: "my-label",
        offset: [-2, -25]
    }).addTo(map);
};

var areaIcon = {
    icon: L.icon({
        iconUrl: 'labels/MonitoringIcon.png',
        iconAnchor: [20, 24]
    })
};

var harvestPoints = new L.GeoJSON.AJAX('labels/dfo_areas_point.json', {
    onEachFeature: onEachPoint,
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, areaIcon);
    }
});

最佳答案

不确定是您问题的根本原因是什么,因为当您尝试从地图中删除它们时,我们会丢失您如何精确地引用它们的点(标记)。

通常,多边形和点(标记)之间没有什么区别,即可实现您所描述的(在特定缩放级别上从地图上删除图层,并在其他缩放级别上将其重新添加)。

请注意,setOpacity is a method for L.Markers,而将其应用于geoCson图层组harvestPoints

可能发生的情况是,您在地图中添加了单独的点(标记)(onEachPoint函数中的最后一条指令),但是尝试从地图中删除图层组harvestPoints。因为似乎从未添加到地图,所以什么也没有发生。

如果要同时打开/关闭harvestPoints图层组中的所有点,则只需将该图层组添加到地图中/从地图中删除,而不是添加单个标记:

var harvestPoints = L.geoJson.ajax('labels/dfo_areas_point.json', {
    onEachFeature: onEachPoint,
    pointToLayer: function (feature, latlng) {
                                // make sure `areaIcon` is an OPTIONS objects
        return L.marker(latlng, areaIcon);
    }
}).addTo(map); // Adding the entire geoJson layer to the map.

map.on("zoomend", function () {
    var newMapZoom = map.getZoom();

    if (newMapZoom >= 13) {
        map.addLayer(harvestPoints);
    } else {
        // Removing entire geoJson layer that contains the points.
        map.removeLayer(harvestPoints);
    }
});


旁注:默认情况下,弹出窗口会在单击时打开,您是否不需要为此添加一个单击监听器?

演示:http://jsfiddle.net/ve2huzxw/62/

08-18 20:52
查看更多