代码之家  ›  专栏  ›  技术社区  ›  Cezar B

在传单中重新应用geojson过滤器

  •  0
  • Cezar B  · 技术社区  · 7 年前

    在传单中,我使用一个变量在geojson的过滤器中插入一个条件,如下所示:

    var stareInt = "start";
    var elements;
    
    var geojsonStyle = {
     radius: 6,
     fillColor: "#6bad9f",
     color: "#FFF",
     className: 'point',
     pane: "pointPanel",
     weight: 1,
     opacity: 0.9,
     fillOpacity: 0.8
    };
    
    
    elements = L.geoJSON(elem_build, {
    pointToLayer: function (feature, latlng) {
        return new L.circleMarker(latlng, geojsonStyle, {
    }).on('click', function() {
        this.bindPopup(feature.properties.grad_int).openPopup();
    });
    },
    
    filter: function(feature, layer) {    
      if (stareInt == "01") {  
        return (feature.properties.grad_int == "very good");
      }
      else if (stareInt == "02") {
        return (feature.properties.grad_int == "good");
      }
      else {
        return feature.properties.grad_int == "bad";            
      }
     },
    
    onEachFeature: onEachFeature
    }).addTo(map);
    

    通过单击按钮激活过滤器,如下所示:

    $("#buttonA").click(function() {
     map.removeLayer(elements);
     stareInt= "01";
     map.addLayer(elements);
    });
    

    但我看到只返回最后一个状态(在本例中是“bad”)。

    我想我必须重新申请过滤器或类似的东西,因为传单不记得它。

    我怎样才能让过滤按钮工作?

    1 回复  |  直到 7 年前
        1
  •  2
  •   IvanSanchez    7 年前

    记住 filter 回调函数运行 一旦 ,当您的 L.GeoJson 已实例化。传单上有 在上重新应用筛选器 L.杰森 当图层被(重新)添加到地图时。这是按设计的。你可以看看这个 the source code for L.GeoJson .

    一种方法是有三个不同的实例 L.杰森 ,每个都应用了不同的筛选器:

    var elements_verygood = L.geoJson(elem_build, {
        filter: function(feat) { return feat.properties.grad_int == "very good"); }
    });
    
    var elements_good = L.geoJson(elem_build, {
        filter: function(feat) { return feat.properties.grad_int == "good"); }
    });
    
    var elements_bad = L.geoJson(elem_build, {
        filter: function(feat) { return feat.properties.grad_int == "bad"); }
    });
    

    然后,您可以使用外部按钮切换内容:

    document.getElementById("buttonA").addEventListener('click', function() {
        map.removeLayer(elements_good);
        map.removeLayer(elements_bad);
        map.addLayer(elements_verygood);
    });
    

    但这也是使用 L.Control.Layers :

    L.control.layers({}, {
        "Very good": elements_verygood,
        "Good": elements_good,
        "Bad": elements_bad,
    }).addTo(map);