Attaching a style to a function after painting

I am using ol.Interaction.Draw

to draw polygons over the map. I want to style individual functions after drawing them.

When I detect an event DRAWEND

, I try to bind the style to the last highlighted function, but only the general layer style appears on the screen, although I can see this when I search in the function 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); 
});

      

+3


source to share


1 answer


The function called setStyle

on is not the one that was just drawn. This is why the function that was just drawn does not have the expected style. (And given your code, I'm really surprised that the function is saved to the map when the drawing is finished.)

The code is wrong / strange in several ways:

  • Reading your code sounds like you think that every call getFeatures

    on a vector layer is returning the same array. This is not true. Each call getFeatures

    actually returns a new array.

  • You are passing an array of functions to the Draw interaction (via an option features

    ). This is not true. The option features

    should be ol.Collection

    .

  • In the callback, drawend

    the event object ( e

    in your code) contains a reference to the drawn function ( e.feature

    ).



So, if you want to keep the drawn objects in 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);

      

+6


source







All Articles