[GIS] prevent features from being created outside an OpenLayers map

featuresopenlayers-2

In our app, we allow users to create features on maps. The boundaries of these features will later be converted into real-life latitude/longitude coordinates, but does not make sense if features are created outside the actual boundaries of the map.

In the above screenshot, I'd like to prevent the blue feature from being drawn so that its upper edge stays inside the actual map.

How could I do that? I couldn't find any reference to this in OpenLayers examples or documentation.

(Currently on 2.12-rc1)

Best Answer

You could use an intersect check as Aragon specifies, combined with your own polygon handler, i've modified a polygon handler that won't let the user finish drawinf if the polygon is self-intersecting:

var myhandler = OpenLayers.Class(OpenLayers.Handler.Polygon, {

    addPoint: function(pixel) {
        var intersect = checkIntersect(this.polygon.geometry);
        if(intersect && this.polygon.geometry.components.length ==1){       
            //do nothing
        }
        else {
            OpenLayers.Handler.Polygon.prototype.addPoint.apply(this, arguments);
            if(intersect){
                this.undo();
            }
        }

    },
});

where the checkIntersect function checks self intersection

if you replace the checkIntersect with a function that checks for intersection with your area bounds, this should work.

use a normal DrawFeatureControl, but with your "myhandler" handler instead of a OpenLayers.Handler.Polygon

EDIT: edited with better implementation

For lines, you could try and subclass the Path handler in a similar way

Related Question