OpenLayers 通过 属性 从 GeoJSON 创建图层

OpenLayers create Layers from GeoJSON by property

我想使用 OpenLayers v5.3.0 创建 Web 应用程序。

我能够将外部 GeoJSON 文件中的所有特征显示为 OSM 层上方的矢量图层,但我的 GeoJSON 文件包含数千个特征,每个特征都由大量属性丰富。

我正在寻找的是一种能够解析 GeoJSON 文件、按属性对其进行过滤的方法(例如,具有 属性 "gender": "f","ethnic_gro": "Latvian", 的所有功能)并仅将那些显示为我的 OSM 基础层之上的附加矢量层。

这是我的 GeoJSON 文件的示例(缩写,只有一个特征):

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [23.114870000000053, 56.845980000000134],
          [19.131050000000164, 50.65641000000013]
        ]
      },
      "properties": {
        "OID_": "0",
        "ethnic_gro": "Latvian",
        "religion": "protestant",
        "marital_st": "widow",
        "status_in_": "NULL",
        "gender": "f",
      }
    }
  ]
}

感谢您的帮助!

您可以在原始要素数组上使用 javascript 数组过滤器来构建新的 GeoJSON 对象:

var filteredGeoJSON = {
  "type": "FeatureCollection",
  "features": fullGeoJSON.features.filter(function(feature){
     return (feature.properties.ethnic_gro == "Latvian" && feature.properties.gender == "f");
  })
};

或使用 forEach 循环构建过滤数组:

var filteredGeoJSON = { 
  "type": "FeatureCollection",
  "features": []
};
fullGeoJSON.features.forEach(function(feature){
  if (feature.properties.ethnic_gro == "Latvian" && feature.properties.gender == "f") {
    filteredGeoJSON.features.push(feature);
  }
});