[GIS] OpenLayers Map Draw polygon Feature inside boundaries

geometryopenlayers

Is it possible to draw polygon inside specific boundaries?

draw_interaction = new ol.interaction.Draw({
    source: vector_layer.getSource(),
    type: /** @type {ol.geom.GeometryType} */ ($geom_type.val())
});

map.addInteraction(draw_interaction);

Specify boundaries area in yellow is it possible to add new Geometry Type inside yellow area only? https://jsfiddle.net/vishal05/wb3m90eb/

Best Answer

You can use ol.geom.Point#getCoordinates() and ol.geom.Polygon#intersectsCoordinate(coordinate) methods together.

I changed your code like this:

function addDrawInteraction() {
    // remove other interactions
    map.removeInteraction(select_interaction);
    map.removeInteraction(modify_interaction);

    // create the interaction
    draw_interaction = new ol.interaction.Draw({
        source: vector_layer.getSource(),
        type: /** @type {ol.geom.GeometryType} */ ($geom_type.val())
    });
    // add it to the map
    map.addInteraction(draw_interaction);
    var isInsideThePolygon=true;
    // when a new feature has been drawn...
    draw_interaction.on('drawend', function(event) {
            if(isInsideThePolygon){
          // create a unique id
          // it is later needed to delete features
          var id = uid();
          // give the feature this id
          event.feature.setId(id);
          // save the changed data
          saveData();
        }
        else{
            setTimeout(function(){
            vector_layer.getSource().removeFeature(event.feature);
          }, 10
          );
        }
    });

    draw_interaction.on('drawstart', function(event) {        
        var drawnPointCoordinates= event.feature.getGeometry().getCoordinates();
        var polyGeometry=polyFeature.getGeometry();
        isInsideThePolygon=polyGeometry.intersectsCoordinate(drawnPointCoordinates);       
    });

}

New JsFiddle link

Related Question