OpenLayers按属性从GeoJSON创建图层

时间:2018-11-11 16:21:49

标签: javascript openlayers geojson

我想使用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",
      }
    }
  ]
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以在原始要素数组上使用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);
  }
});