I am using ol.Interaction.Draw
to draw polygons atop a map. I want to style the individual features after they're drawn.
When I detect a DRAWEND
event, I try to attach a style to the last feature drawn, but only the general layer styling appears onscreen, although I see it when I search in the feature itself via the debugger.
map.addInteraction( drawInter = new ol.interaction.Draw({
features: drawLayer.getFeatures(),
type: "Polygon"
})
);
drawInter.on('drawend', function(e) {
var style = new ol.style.Style({
fill: new ol.style.Fill({ color: newColor })
});
var features = drawLayer.getFeatures().getArray();
var last = features.length-1;
features[last].setStyle(style);
});
The feature you call setStyle
on is not the one that was just drawn. This is why the feature that was just drawn doesn't have the expected style. (And given your code I am actually surprised the feature persists on the map when the drawing is finished.)
Your code is incorrect/strange in multiple ways:
Reading your code it sounds like you think that each call to getFeatures
on the vector layer returns the same array. It's not the case. Each call to getFeatures
actually returns a new array.
You pass an array of features to the Draw interaction (through the features
option). This is incorrect. The features
option should an ol.Collection
.
In the drawend
callback the event object (e
in your code) includes a reference to the drawn feature (e.feature
).
So, if you want to persist the drawn features into a vector layer, you can use the following:
var draw = new ol.interaction.Draw({
type: 'Polygon',
source: drawLayer.getSource()
});
draw.on('drawend', function(e) {
var style = new ol.style.Style({
// ...
});
e.feature.setStyle(style);
});
map.addInteraction(draw);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With