I have a map which is implemented using Openlayers 4. It loads a GeoJSON vector which defines the boundaries of a particular country. The user is allowed to draw and edit polygons to define subregions of this countries which will be saved to DB as GeoJSON data. I need to check if the polygon drawn by the user is completly within the boundaries of the country. How can i achieve this. I am adding the code snippet where i capture the subregion layer polygon drawn by the user here.

feature.on('change', function(event) {
          var format = new ol.format.GeoJSON({featureProjection: 'EPSG:3857'});

          var subregion_features = format.writeFeatures(vector.getSource().getFeatures());

          //code to check if the newly drawn polygon is inside the master layer (whole country layer)


2 Answers 2


You could use the JSTS library, which can be used to do all sorts of operations between geometries. For instance, you could write a MultiPolygon geometry containing all your sub regions and use the contains method of the JSTS Geometry class.

There's an example that features JSTS with OpenLayers. It shows how to use the buffer method, you could start from there to learn how to use the contains method in JSTS. You would need to convert the geometry object from OL3 to JSTS first. That's shown in the example.

// convert the OpenLayers geometry to a JSTS geometry
var jstsGeom = parser.read(feature.getGeometry());


var contains = jstsGeom.contains(jstsGeom2); // should work

With this, you would be able to check if the drawn geometry is inside the exact boundaries of the regions


An example how to check it in OpenLayers 6.x version and typescript:

let xy:any = this.getCenterOfExtent(feature.getGeometry()?.getExtent());
let insideFeature:boolean = selectedFeature.getGeometry().containsXY(xy[0],xy[1]));


    var X = extent[0] + (extent[2]-extent[0])/2;
    var Y = extent[1] + (extent[3]-extent[1])/2;
    return [X, Y];

Probably there will be an easier solution with newer versions of Openlayers in the future.

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.