如何从现有文件创建 geoJson 文件的子集

How to create a subset of geoJson file from existing file

我有一个 geoJSON 文件如下:

    var geoJSON=    
    {

    "type":"FeatureCollection",

    "features": [                                             
        {"type": "Feature","geometry":{"type":"LineString", "coordinates":[[102.463303,36.447488],[102.514114,36.439755]]},"properties": {"id":"01","points":9}},
        {"type": "Feature","geometry":{"type":"LineString", "coordinates":[[102.593765,36.414341],[102.634964,36.402183]]},"properties": {"id":"02","points":8}},
        {"type": "Feature","geometry":{"type":"LineString", "coordinates":[[102.880783,36.485038],[102.882156,36.561187]]},"properties":{"id":"03","points":10}}

........
and so on
                ]};

由此我想创建一个变量 filtered_geoJSON,其中只有 >=9 的点可用,如下所示:

var filtered_geoJSON=    
        {

    "type":"FeatureCollection",

    "features": [                                             
        {"type": "Feature","geometry":{"type":"LineString", "coordinates":[[102.463303,36.447488],[102.514114,36.439755]]},"properties": {"id":"01","points":9}},
        {"type": "Feature","geometry":{"type":"LineString", "coordinates":[[102.880783,36.485038],[102.882156,36.561187]]},"properties":{"id":"03","points":10}}

........
and so on
                ]};

因为每次我更新每个线串的点时

  geoJSON['features'][i]['properties']['points']=data[i].points;

所以我想每次都创建 filtered_geoJSON 变量并将其传递给

L.geoJson(filtered_geoJSON, {
                     style: style,
                     onEachFeature: onEachFeature
                }).addTo(map);

所以我只绘制点数 >=9 的点。

所以我尝试了

var top_geoJSON={"type":"FeatureCollection","features": []};
            var c=0;
            for (i = 0; i<40000; i++) { 


                if(geoJSON['features'][i]['properties']['score']!=data[i].points){
                      links['features'][i]['properties']['score']=data[i].score;
                }

                if(geoJSON['features'][i]['properties']['points']>9){
                    filtered_geoJSON[c]=geoJSON['features'][i];
                     c++;
                }  

filtered_geoJSON 在那里,但没有在地图上绘制线条。

感谢任何帮助。

Leaflet L.geoJSON 工厂有一个 filter 选项,您可以使用它来提供整个 geoJSON 数据,并让 Leaflet 仅保留满足您指定条件的数据(即 feature.properties.points >= 9 在你的情况下)。

当您在更新 points 重新构建 您的 filtered_geoJSON 变量时,您必须从中构建一个新的 L.geoJSON在你在地图上找到一些东西之前。

此外,即使直接更改 geoJSON 数据,Leaflet 也不会通过 filter 再次对其进行评估,因此如果某些特征低于 9,或者某些新特征高于 9,这将不会自动反映在地图上。

最简单的解决方案是删除您之前创建的 L.geoJSON 图层组,并使用更新后的 geoJSON 数据(和相同的过滤器)构建一个新图层组,以便 Leaflet 重新再次评估您的功能。

一个稍微复杂的解决方案是直接遍历 L.geoJSON 层组子层(而不是您的原始 geoJSON 数据),通常使用 eachLayer,更新它们的 feature.properties.points 并确定它现在应该隐藏还是显示回来。您最初需要在不使用任何过滤器的情况下创建 L.geoJSON 图层组,然后手动将子图层添加到地图/从地图中删除它们。当然你也可以使用中间的 L.layerGroup.