OpenLayers is an powerful map api to develop map based applications. But to perform complex spatial operations like splitting a polygon, merging two polygons etc., we need to find another way to accomplish these operations. OpenLayers can’t do these operations on its own.
In this tutorial, we are going to develop a Polygon Splitter tool that will split the polygon into two parts by a line.
JSTS library can be easily integrated with OpenLayers. All you need to do is import the JSTS library using the script tag and we can start using it.
Let’s split the Polygon by a Line. We can access JSTS functionalities using the jsts object. At line number 7 in the below code snippet, we are creating an OpenLayers parser that can parse OpenLayer’s geometry object to the native geometry type of jsts. At line number 9, we are creating an OpenLayers Line geometry from line drawing on the map.
So basically, we need the following two operations to split a polygon by a line:
1. Union of Line and Polygon
2. Polygonization operation that will construct all simple polygons on a set of points genrated from the union of Line and Polygon.
At lines number 15 and 16, we are parsing Polygon and Line to jsts native type.
At line number 19, we are performing a union of Polygon and Line.
At lines number 20 and 23, we are using Polygonizer to split the polygon by a line. The Polygonizer will construct two polygons from the union of polygon and line.
Note: The Polygon and Line should be completely intersected with each other else Polygonizer will return only a single polygon
At line number 26, we are getting splitted polygons from Polygonizer.
That’s it. We have successfully splitted the polygon.
In the rest part of the code i.e. after line number 29, we are providing measurement labels for split polygons and tweaking some styles of feature
It should be noted that we are dynamically splitting the polygon which means that at every geometry change event of the drawn line, we will split the polygon and will also provide the dynamic measurement and styling.