How do you split an OpenLayers Vector Feature (Polygon or a LineString)?
i.e
ux: select feature, select a 'split' UI button, draw a split on-top of the polygon or through the line. The feature would then be split into multiple features that I have access too.
Are there any Split functions/interactions from either OpenLayers or a 3rd party library that you can use or how would you implement this manually?
Best Answer
Solution below is based upon port and improvement of similar solution for Leaflet (see Splitting A polygon into multiple polygon by multiple line strings in Leaflet and turf.js).
Cutting of polygon with line is done with the help of Turf.js library. Turf.js library does not have explicit method to split polygon with line. The most convenient method for this purpose is then
turf.difference(poly1, poly2)
, which cuts out second polygon from first. If second polygon is very thin and long rectangle (line with small 'height'), this can be used as a split method.This is done in two steps. First step is to 'fatten' dividing line to one side, cut polygon by it and take into account split polygon(s) one the opposite side of the line. Then dividing line is 'fattened' to the other side, polygon is cut by it and split polygon(s) on opposite side is taken into account.
This way polygon of any shape can be cut with line of any shape.
Result of cut is feature collection of cut polygons, where each polygon has feature
id
in the formidPrefixN.M
, whereidPrefix
is input parameter to cut function,N
is number of cut side (1 or 2) andM
is sequential number of polygon on relevant side.Code of cut function:
Example of usage of this function is available at JSFiddle: https://jsfiddle.net/TomazicM/157s3Lmt/. Example allows splitting of polygons multiple times with lines of any shape.
At each step (split) the following layers and arrays are updated:
drawnPolygons
contains all polygons, split and unsplitdrawnLines
contains all lines used for splittingpolygons
contains all polygons that correspond to drawnPolygons layerThe main part of the code:
Here is an example of complex polygon cut: