I have a project that uses Openlayers in order to draw, edit and show multiple polygons. One of the features I want to add to the project is the automatic avoiding of overlapping features.
When a user draws a new features. The application should check if any of the already existing features is being overlapped by the new feature. This is already available thanks to the Turf.js library: Stackoverflow discussion on overlapping features.
The next step I want to add is the ability to automatically cut off and remove the excess areas from the new feature that overlaps the existing ones. I have searched on the Turf.js documentation but I cannot a function that does that.
With the help of Mike I have created a solution that works. I loop over all features that exist in the VectorLayer. I first check if the feature is indeed a Polygon. Then I convert the features into Turf Polygon objects and check if they intersect. If they intersect I use the difference function from Turf and set the coordinates of the feature to the generated Polygon.
const removeOverlappingAreasWithExistingFeatures = (feature) => {
const format = new GeoJSON();
store.state.layers.drawingLayer.getFeatures().forEach((existingFeature) => {
if (
existingFeature.getGeometry().getType() !== 'Polygon' ||
!existingFeature.get('description') ||
existingFeature.get('description') === feature.get('description')
)
return;
var featurePoly = format.writeFeatureObject(feature);
var existingFeaturePoly = format.writeFeatureObject(existingFeature);
const intersection = turf.intersect(featurePoly, existingFeaturePoly);
if (intersection) {
var difference = turf.difference(featurePoly, intersection);
difference.geometry.coordinates =
difference.geometry.coordinates.filter(
(coordinate) => coordinate.length > 0
);
feature.setGeometry(format.readFeature(difference).getGeometry());
}
});
return feature;
};