【问题标题】:Leaflet: Update GeoJson filter?传单:更新 GeoJson 过滤器?
【发布时间】:2013-04-15 10:37:38
【问题描述】:

我想用数据填充 GeoJson 层,然后动态过滤要显示的特征。

我已经让过滤器功能工作,但我不知道如何更改过滤器然后刷新图层。

添加数据后有什么方法可以更新过滤器吗?

【问题讨论】:

    标签: javascript leaflet geojson


    【解决方案1】:

    我通过根据功能的属性将每种功能类型添加到不同的LayerGroup 来做到这一点。例如

    GeoJSON

    var data =[
      {
       type: "Feature",
       properties: {
          type: "type1"
       },
       geometry: {
          type: "Point",
          coordinates: [-1.252,52.107]
       }
      },
      {
       type: "Feature",
       properties: {
          type: "type2"
       },
       geometry: {
          type: "Point",
          coordinates: [-2.252,54.107]
       }
      }
    ];
    

    创建GeoJSON

    //array to store layers for each feature type
    var mapLayerGroups = [];
    
    //draw GEOJSON - don't add the GEOJSON layer to the map here
    L.geoJson(data, {onEachFeature: onEachFeature})//.addTo(map);
    
    /*
     *for all features create a layerGroup for each feature type and add the feature to the    layerGroup
    */
    function onEachFeature(feature, featureLayer) {
    
        //does layerGroup already exist? if not create it and add to map
        var lg = mapLayerGroups[feature.properties.type];
    
        if (lg === undefined) {
            lg = new L.layerGroup();
            //add the layer to the map
            lg.addTo(map);
            //store layer
            mapLayerGroups[feature.properties.type] = lg;
        }
    
        //add the feature to the layer
        lg.addLayer(featureLayer);      
    }
    

    然后您可以调用 Leaflet map.addLayer/removeLayer 函数,例如

    //Show layerGroup with feature of "type1"
    showLayer("type1");
    
    /*
    * show/hide layerGroup   
    */
    function showLayer(id) {
        var lg = mapLayerGroups[id];
        map.addLayer(lg);   
    }
    function hideLayer(id) {
        var lg = mapLayerGroups[id];
        map.removeLayer(lg);   
    }
    

    【讨论】:

    • 如何更改每个图层组的标记图标?
    【解决方案2】:

    GeoJSON addData 方法中,首先检查数据是否是特征的集合,在这种情况下,每个特征都会调用该方法。

    然后按如下方式应用过滤器:

    var options = this.options;
    if (options.filter && !options.filter(geojson)) { return; }
    

    因此,如果过滤器在您添加数据时将其过滤掉,则不会在任何地方存储或记住它。更改过滤器不会使数据突然重新出现。

    您可以保留对 geojson 的引用,并在更改过滤器时重新初始化图层。

    【讨论】:

    • 谢谢,重新初始化图层是否意味着 addLayer / removeLayer?
    • 我怀疑你也可以打电话给initialize(newgeojson, options),但我还没试过。删除和添加肯定会起作用。
    • 实际上map.removeLayer(gj) 然后map.addLayer(gj) 不起作用。
    • 来自文档 -> 注意:动态更改过滤器选项只会对新添加的数据产生影响。它不会重新评估已包含的功能。
    【解决方案3】:

    请参见下面的示例,您有一张地图和一个 myBus 图层。

    map.removeLayer(myBus);
    
    ...add your data edit something ...
    
    myBus.addTo(map);
    

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2014-01-20
      • 2014-12-31
      相关资源
      最近更新 更多