4

I created a vector and a drawing interaction:

// Create feature collection and vector
var featureCollection = new ol.Collection();
var vectorSource = new ol.source.Vector({
    features: featureCollection
});
featureOverlay = new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 50, 0, 0.5'
        })
    })
});
featureOverlay.setMap(map);


// create drawing interaction
drawingInteraction = new ol.interaction.Draw({
    features: featureCollection,
    type: 'Polygon'
});

map.addInteraction(drawingInteraction);

Now I would like to let a user change the drawing style, which, when called separately, can be done like this:

var s = new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(0, 255, 0, 0.5'
            })
});

featureOverlay.setStyle(s);

This works fine, but it changes the style of all the drawn polygons. However, I would like to change the new ones only and keep the styling of the existing ones.

For example, I draw my initial red polygons:

enter image description here

Then the user switches styles by firing the setStyle() method above, but then all polygons turn green, not just the one I will set after firing the method and drawing a new polygon:

enter image description here

  • 1
    It will be a little more tricky, but it can be accomplished. You have to set the style of the feature instead of the layer. – Gabor Farkas Nov 28 '16 at 10:10
  • That helped me solve it! I posted the code below! Thank you so much! – BritishSteel Nov 28 '16 at 10:51
5

Thanks to Gabor Farkas I was able to fix the issue. The style should not be set on the vector but on the single feature, that will be drawn.

This can be done by setting the feature's style once drawing begins:

drawingInteraction = new ol.interaction.Draw({
    features: featureCollection,
    type: geomType
});

drawingInteraction.on('drawstart',function(event){
    var s = new ol.style.Style({
        fill: new ol.style.Fill({
            color: drawingPolyStyle.colors
        })
    });

    event.feature.setStyle(s);

});

map.addInteraction(drawingInteraction);

In the example drawingPolyStyle is an object that holds the colors that were chosen in a color picker menu.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.