Split a Polygon with holes by Line in OpenLayers

Polygon with holes Split by Line in OpenLayers

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.

This tutorial is the extension to following tutorial. If you have not gone through this, then please go through this. In that tutorial, we covered how to split a polygon(without holes) a line.

Click here to get the full source code for this tutorial.

Click here to test the live demo.

In this tutorial, we split those polygons which have with holes by line. We will use JSTS(Java Script Topology Suit) library which is used for performing geometrical operations using JavaScript.

By default, JSTS will split the polygon(with holes) in regular subdivided polygon which will not have holes. Something like below. Even though, our polygon have holes, but when it is split, the holes information is gone.

Polygon splitting default behavior in JSTS

But thankfully, we have good features in JSTS(JavaScript Topology Suite). Using those we can achieve our goal.

When JSTS read a polygon geometry, it also read it’s holes as a separate geometry. In the following image, we have printed an JSTS polygon object in console. You can see, it has holes information.

JSTS provides other spatial operations like union, difference and intersection. Basically, you can add two geometries, subtract two geometries with each other. In our case, we will use difference operation. Following image will make it clear

Credit: Microsoft

As we discussed above, JSTS will ignore holes when splitting. In order to maintain holes after splitting, we will subtract holes from the split polygons i.e. we will perform difference operation with holes after split. This trick will perfectly split polygon with holes.

In the following code snippet, first we are getting holes of polygon at line number 20 and then at line number 40 we are subtracting these holes from split polygon. This will perfectly split or divide the polygon with holes.


Click here to get the full source code for this tutorial.

Click here to test the live demo.

1 thought on “Split a Polygon with holes by Line in OpenLayers”

  1. Pingback: Draw Holes in OpenLayers Polygon - Spatial Dev Guru

Leave a ReplyCancel reply