Take the 2-minute tour ×

I have two json arrays, one for background polygon and one for other polygon. And from them, I got two polygon layers.

backgroundLayer = new OpenLayers.Layer.Vector("Background Layer", {styleMap: backgroundStyleMap} );
totalAreaPolygon = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]))

And same for other polygon.

How can I subtract the other polygon from background polygon as shown in the picture (right polygon).

enter image description here

This is one of the examples from OpenLayers. http://openlayers.org/dev/examples/donut.html

share|improve this question
Where'd the 'geodesic' in your title come from? And is your end goal to create a donut polygon? –  R.K. Feb 6 '12 at 1:15
Oh... Yes, I want to create a donut polygon by subtracting smallLayer from backgroundLayer. –  Michelle Chan Feb 6 '12 at 5:29
add comment

2 Answers

up vote 3 down vote accepted

You can create a new Polygon with 2 components or addComponent to the existing polygon.

Notice what the polygon constructor says in the documentation.

The first ring (this.component[0])is the outer bounds of the polygon and all subsequent rings (this.component[1-n]) are internal holes.

Basically the first component (LinearRing) in the polygon is the perimeter and the 2nd is the donut hole.

And this is exactly how the Polygon Handler (OpenLayers.Handler.Polygon) does it in the openlayers example you posted.

Here's a function that will return a new feature polygon from two other features:

function Subtract(bigFeature, smallFeature) {

    var newPolygon = new OpenLayers.Geometry.Polygon(bigFeature.geometry.components);
    var newFeature = new OpenLayers.Feature.Vector(newPolygon);
    //Add Inner DONUT HOLE!

    return newFeature;


Here's a DEMO of the usage.

var newFeature = Subtract(layerBig.features[0], layerSmall.features[0]);
share|improve this answer
Took your demo and created a more advanced version for anyone interested: jsfiddle.net/colllin/pRSt7 –  colllin Sep 5 '13 at 22:32
add comment

Have you checked JSTS? Is a port of the popular Java Topology Suite to JavaScript to perform graphic operations like the difference you are asking for but I haven't used it and it's pretty new so no idea from first hand.

share|improve this answer
JSTS worked great for me for merging two polygons via the union function, but it wasn't obvious how to subtract a polygon. It would be great to see some code for that if you have any. –  colllin Sep 3 '13 at 18:32
add comment

Your Answer


