1

I want to filter GeoJSON features with bbox condition in OpenLayers 7, so I coded like this:

  const geojson = (Some GeoJSON definition);
  const projection = (Some projection definition);


  const geojsonSource = new ol.source.Vector({
    features: new ol.format.GeoJSON().readFeatures(geojson, {
      featureProjection: projection,
      dataProjection: "EPSG:4326",
      filter: ol.format.filter.bbox("geometry", projection.getExtent(), projection.getCode())
    }),
  });

But no features were filtered with this code. How can I filter them?

1 Answer 1

0

I solved this by creating function like this:

const filterGeoJSON = (source, options) => {
  const extent = options.extent;
  const projectTo = options.projectTo;
  const retSource = new ol.source.Vector();
  source.forEachFeature((f) => {
    let retF = f.clone();
    if (projectTo) {
      retF.setGeometry(retF.getGeometry().transform("EPSG:4326", projectTo));
    }
    if (!extent || retF.getGeometry().intersectsExtent(extent)) {
      retSource.addFeature(retF);
    }
  });
  return retSource;
};

const geojson = (Some GeoJSON definition);
const projection = (Some projection definition);

const geojsonSource = new ol.source.Vector({
  features: new ol.format.GeoJSON().readFeatures(geojson, {
    featureProjection: "EPSG:4326",
    dataProjection: "EPSG:4326",
  }), 
});

const expectedSource = filterGeoJSON(geojsonSource, {
  extent: projection.getExtent(),
  projectTo: projection
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.