如何删除包含它的topojson图层时的传单标签

时间:2015-07-29 04:35:49

标签: javascript jquery leaflet topojson

我正在尝试创建一个可视化某些数据的交互式地图。

我使用了传单地图和topojson图层。接下来,我尝试使用leaflet标签插件在每个topojson多边形上添加静态标签,即标签应始终在那里,不应对mouseover事件做出反应。

我尝试使用bindLabel()实施noHide:true方法,但似乎无效。因此,我实施了为此问题提供的解决方案Simple label on a leaflet (geojson) polygon。我成功添加了静态标签。

然后,我有一个函数删除click事件上的topojson多边形。我本来应该删除这个特殊多边形上的标签,但它似乎无法实现。

以下是我添加topojson图层和标签的方法:

function addRegions(map) {
    var regionLayer = new L.TopoJSON();
    $.getJSON('region.topo.json').done(addRegionData);

    function addRegionData(topoData) {
        regionLayer.addData(topoData);
        regionLayer.addTo(map);
        regionLayer.eachLayer(addLabel);
        regionLayer.eachLayer(handleLayer);
    }
    function handleLayer(layer) {
        layer.on({
            click: clickAction
        });
    }

// Here's the code for adding label
    function addLabel(layer) {
        var label = new L.Label();  
        label.setContent(layer.feature.properties.REGION);
        label.setLatLng(layer.getBounds().getCenter());
        map.showLabel(label);
    }

// Here's the code that removes a polygon when it is clicked and retains the previously removed polygon
    function clickAction(e) {
        regionLayer.eachLayer(function(layer){
            map.addLayer(layer);
        });
        var layer = e.target;
        map.removeLayer(layer);
    }
}

到目前为止,此代码在单击时删除了topojson多边形,但标签仍然存在。

我必须删除已移除的特定多边形上的标签,但将标签保留在其他多边形上。

此外,当单击另一个多边形时,应该将其删除,但应保留先前删除的标签,因为还保留了先前删除的多边形。

我不能,因为我的生活想到了如何实现这一点。请帮我。

1 个答案:

答案 0 :(得分:5)

<强>释

首先,您需要维护一个labels_array,以便存储标签,以便在需要时删除。

其次,维护另一个unique_property_array,您需要在topojson文件中存储您拥有的唯一属性。

第三,当用户点击任何功能时,我们会获得点击的功能属性并与我们的unique_property_array匹配,获取匹配值的索引并从{删除该索引{1}}。此外,先添加标签删除。

<强>码块

首先,您需要有三个全局变量

labels_array

其次,以这种方式修改您的var labels_array=[]; var unique_property_array=[]; var labelIndexToRemove=''; 功能

addLabel()

最后,以这种方式修改function addLabel(layer) { var label = new L.Label(); label.setContent(layer.feature.properties.REGION); label.setLatLng(layer.getBounds().getCenter()); map.showLabel(label); //below two lines are new labels_array.push(label); unique_property_array.push(layer.feature.properties.region); } 功能

clickAction()

试试这个并告诉我它是否有效。祝你好运