How to catch event after drawend added to source in OL3?
Asked Answered
R

1

8

I'd like to update a list after each feature has been drawn to a map.

When I use drawend to catch the finishing of a drawing, the feature being drawn is not yet added to the vector source at that moment.

So

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

draw.on('drawend', function () {
    console.log(source.getFeatures().length)
});

map.addInteraction(draw);

Will output 0 when the first point has been added.

How can I catch the state of the map when the drawing is finished and the feature has been added to the vector source? Thus I'm looking for a state when source.getFeatures().length would be 1 on an empty map.

Rech answered 29/8, 2016 at 22:28 Comment(2)
Answer here.Retro
@JonatasWalker thanks a lot, funny both questions were asked almost at the same time. If possible I'd recommend adding that as an event to the draw interaction.Rech
P
14

You can always try what @jonatas suggest. It should do the job you look for. One more workaround is to get the currently drawn feature from the event itself and add it to your features array. Check this

draw.on('drawend', function (e) {
var currentFeature = e.feature;//this is the feature fired the event
var restOfFeats = source.getFeatures();//rest of feats
var allFeats = restOfFeats.concat(currentFeature);//concatenate the event feat to the array of source feats
console.log(allFeats.length)
});
Prissie answered 30/8, 2016 at 7:40 Comment(2)
wouldn't this cause a duplicate feature ?Acidfast
Each time 'drawend' event fires you have a new array of features (allFeats) . No duplicates.Prissie

© 2022 - 2024 — McMap. All rights reserved.