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

  • Where'd the 'geodesic' in your title come from? And is your end goal to create a donut polygon?
    – R.K.
    Feb 6, 2012 at 1:15
  • Oh... Yes, I want to create a donut polygon by subtracting smallLayer from backgroundLayer. Feb 6, 2012 at 5:29

2 Answers 2


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.

Here's an example of using the difference function:

function subtractFromFeature(positiveFeature, negativeFeature) {
    var parser = new jsts.io.OpenLayersParser();
    return new OpenLayers.Feature.Vector(

// Where `bigFeature` and `littleFeature` are instances of OpenLayers.Feature.Vector
var differenceFeature = subtractFromFeature(bigFeature, littleFeature);

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]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.