Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching style to feature after drawing

Tags:

openlayers-3

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); 
});
like image 843
Bill Avatar asked Mar 18 '23 11:03

Bill


1 Answers

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);
like image 106
erilem Avatar answered May 05 '23 04:05

erilem