Search code examples
openlayers-3

Dynamically change vector style in openlayers 3


I am using the ol.interaction.Draw method to draw a polygon on a map.

I don't want the user to be able to draw a polygon that is too big, or that intersects itself, so when either of those conditions are met (which I have already written code to determine), I want the lines of my polygon to change from the default blue color to red so that the user knows their polygon is not acceptable.

I know how to set the style originally for the Draw functionality but can't figure out getting the style to dynamically change on the fly, while the user is still drawing.


Solution

  • The style argument of ol.layer.Vector and also of ol.interaction.Draw can be a StyleFunction which receives the feature and the current map resolution. You can check in this function if your geometry is valid and return an appropriate style.

    Here an example where the color changes from green to red if the geometry has more than 2 coordinates:

    var drawStyle = function(feature, resolution) {
        var color = 'green';
        if(feature.getGeometry().getCoordinates().length > 2) {
            color = 'red';
        }
        return [new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: color,
                width: 2
            }),
            ...
        })];
    };
    
    var draw = new ol.interaction.Draw({
        ...
        style: drawStyle
    });
    

    http://jsfiddle.net/sad71377/