# How to merge two Polygons in OpenLayers?

I have two polygons.

``````polygon1 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing1]))
polygon2 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing2]))
``````

How can I merge the two polygons into one using OpenLayers?

• Please explain your question, I'm not sure what do you mean. – drnextgis Feb 8 '12 at 7:57

For geometry manipulation on client side you can use JSTS Topology Suite. Here is my little example of solving your problem: Union example. Source code:

``````var reader = new jsts.io.WKTReader();

var a = reader.read('POLYGON((10 10, 100 10, 100 100, 10 100, 10 10))');
var b = reader.read('POLYGON((50 50, 200 50, 200 200, 50 200, 50 50))');

var union = a.union(b);

var parser = new jsts.io.OpenLayersParser();

union = parser.write(union);

var map = new OpenLayers.Map('map', {
maxExtent: new OpenLayers.Bounds(0, 0, 300, 300),
maxResolution: 100,
units: 'm',
});

var layer = new OpenLayers.Layer.Vector('test', {isBaseLayer: true});

var unionOutput = new OpenLayers.Feature.Vector(union, null, { fillColor: 'green', fillOpacity: 1});

map.zoomToMaxExtent();
``````
• (+1) Always learning something new here. JSTS looks very handy. – CaptDragon Feb 8 '12 at 14:29
• Nice handy fiddle example. Kudos :) – Rob Quincey May 23 '13 at 8:49

What I understand from your question is that you want merge two polygon features. I think you have to do this on the server side with ST_Union feauture which is in PostGIS Geometry Processing Functions. Then you can get the result and add this to your app. whatever you want. To merge...

In postgis you can union lots of polygons like this:

``````SELECT ST_AsText(ST_Union(ST_GeomFromText('POINT(1 2)'),
ST_GeomFromText('POINT(1 2)') ) );
``````

First of all you have to make some openlayers request for your geo collections.

And in GeoDjango you can do this easily with GeoDjango Topological Methods..

``````polygon.union( secondpolygon )

GEOSGeometry.union(other)
Returns a GEOSGeometry representing all the points in this geometry and the other.
``````

I hope this helps you...

Every polygon is consider as one feature. when ever you add the polygon to the vector layer, that feature is stored over there. and you can get independent features from the layer object.