[GIS] How to clear a vector layer before drawstart in openlayers 3

javascriptopenlayers

I have a vector layer in OL3 which I want to auto clear when drawing a Point feature (which means there is always max 1 feature in the layer).

Problem is that when I listen to drawstart (ol.interaction.draw) or to featureadd (ol.layer.vector) they are fired after feature is added and thus I can't clear the layer without them be deleted.

how can I workaround this ?

* Edit *
I've noticed the drawstart event work when the draw type isn't Point , but I want to add points and thus my problem.

Best Answer

Points are a bit tricky because the drawstart and drawend events are driven from the same mouse click. To support all geometry types, have a look at the sample code below.

If you only ever need to support the ol.geom.Point type, then just use the drawend event and don't worry about the rest.

Sample Code

var geomType, lastFeature;

var source = new ol.source.Vector({
    wrapX: false
});

var draw = new ol.interaction.Draw({
    source: source,
    type: geomType
});

// removes the last feature from the vector source.
var removeLastFeature = function() {
    if (lastFeature)
      source.removeFeature(lastFeature);
};

// On draw start for polygon, line and circle types we need to 
// remove the previous feature so that it doesn't show.
draw.on('drawstart', function (e) {

    // Filter on all BUT points
    if (geomType !== 'Point')) {
       source.clear();  // implicit remove of last feature.
    }

});

// When a drawing ends for a point feature, remove the last feature
draw.on('drawend', function (e) {

    // Filter on points ONLY
    if (geomType === 'Point') {
        removeLastFeature();
    }
    lastFeature = e.feature;

});

map.addInteraction(draw);

jsFiddle

See a complete example here that handles all geometry types: https://jsfiddle.net/abb54n79/1/