[GIS] Openlayers remove previously drawn polygon on starting to draw next one

featuresopenlayers-2polygonvector

Objective:

At any point of time there SHOULD only be zero/one polygon(s) on a vector layer with a polygon control. I need the previous polygon to be removed as soon as user starts drawing the first vertex of the next polygon.

Code:

var map = new OpenLayers.Map(mapDiv, options);
var tempLayer = new OpenLayers.Layer.Vector("Temp Layer");
map.addLayer(tempLayer);

var polyControl = new OpenLayers.Control.DrawFeature(tempLayer,OpenLayers.Handler.Polygon);

polyControl.events.register('featureadded', ' ', removeExistingPolygon);

function removeExistingPolygon(feature) //Assuming event listener gets a feature object
//Written mainly with featureadded in mind
{
  if(feature.layer.features.length > 1){
    feature.layer.removeFeatures(feature.layer.features[0]);
  }
}

tempLayer.events.register(<event_name>, ' ', <prev_polygon_removal_function>);

Question:

What event_name and function should I use to attain the objective? I have tried 'sketchstarted' on tempLayer but it gets triggered even before user starts to draw a polygon. 'vertexmodified' doesn't seem to work at all.

Objective is partially satisfied when using featureadded with polyControl but in that case the first polygon remains visible till the second one is completed.

Any pointers on how to proceed are most appreciated. Thanks.

Best Answer

You kind of have catch-22 or at minimum not detailed enough requirements. Specifically - do you want to remove the 1st feature as SOON as the user starts drawing a new feature? Or when they're done? Because you could end up blowing out your 1st feature and user cancels out of drawing 2nd feature and then you have nothing.

You have 2 additional things you can register:

1) Register to listen for the Control's activate event. When the drawing tool is activated, just blow out any features in the layer.
1a) And by the way, it's better to just say layer.removeAllFeatures() instead of the way you have it.

2) Register to listen for the Layer's beforefeatureadded event and work your logic in there. http://dev.openlayers.org/docs/files/OpenLayers/Layer/Vector-js.html#OpenLayers.Layer.Vector.events