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/