OpenLayers create Layers from GeoJSON by property

做~自己de王妃 提交于 2020-03-05 07:54:32

问题


I want to use OpenLayers v5.3.0 to create a Web application.

I’m able to show all features from a external GeoJSON File as a Vector Layer above a OSM Layer, but my GeoJSON File holds thousands of features, each enriched by a lot of properties.

What I’m looking at is a way to be able to parse the GeoJSON File, filter it by properties (e.g. all features with the property "gender": "f", or "ethnic_gro": "Latvian",) and display only those as an additional Vector Layer above my OSM Base Layer.

This is an example of my GeoJSON File (abbriviated, with only one Feature):

{
  "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",
      }
    }
  ]
}

Thanks for any help!


回答1:


You could use a javascript array filter on the original features array to build a new GeoJSON object:

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

or use a forEach loop to build a filtered array:

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


来源:https://stackoverflow.com/questions/53250709/openlayers-create-layers-from-geojson-by-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!