Merge Two Polygons in OpenLayers

Merge Two Polygons in OpenLayers

In this post, we will merge two polygons in OpenLayers(polygons that intersect each other) into one polygon as shown in the above GIF image. The merging of two polygons is also known as the union of two polygons. In the last tutorial, we demonstrated how we can split a polygon by a line into two parts in OpenLayers using JSTS.

If you are a first-time reader of this blog, I would recommend going through the following tutorial on splitting polygon into two parts. It would make understanding this tutorial easy for you.

Split a Polygon by Line in OpenLayers

Before moving forward, we will have a quick look at JSTS(JavaScript Topology Suite). JSTS is a javascript library that allows performing complex spatial/geometrical operations on the frontend. We will use this library to merge two adjacent polygons into one. Merging is also known as the union of two geometry.

But to perform complex spatial operations like splitting a polygon, merging two polygons etc., we will use JSTS.

Let’s dive into the coding part. The following function in the code snippet will merge two adjacent polygons. In line 8, we are creating an OpenLayers parser using JSTS. This parser is required to convert the geometry object from OpenLayers type to JSTS type because we are using JSTS for the merge operation.

In lines 11 and 12, we are parsing the OpenLayers polygons into JSTS type. Once OpenLayers polygons are parsed into JSTS type, we can perform any geometrical/spatial operations on them using JSTS.

In line 15, we are merging the polygons into one. Here we have used the union function of JSTS to merge the polygons. Congratulations, you have successfully merged the two polygons into one.

After that, we are removing the existing polygons from the vector layer and adding the merged polygon to the vector layer.

That’s it. We have successfully merged two adjacent polygons into one. Click on following links to get the full code and live demo.

To get the full code for this tutorial, click on this link.

To check the fully working demo, click on this link.

1 thought on “Merge Two Polygons in OpenLayers”

  1. Pingback: View, Layer and Source in OpenLayers-Part 2 - Spatial Dev Guru

Leave a Reply Cancel reply