简体   繁体   中英

OpenLayers create Layers from GeoJSON by property

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 (eg 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!

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);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM