0

Please look at https://stackoverflow.com/questions/29655662/dynamic-styles-in-openlayers-3 and https://stackoverflow.com/questions/33251893/how-to-dynamically-style-cluster-layer-without-style-function.

I have a Vector layer with some features I load from a server in GeoJSON format.

    var vectorSource = new ol.source.Vector();

    var features = new ol.format.GeoJSON().readFeatures( featuresObj , {
        featureProjection: 'EPSG:4326'
    });

    for ( var i = 0; i < features.length; i++ ) {
        features[i].setStyle( defaultStyle );   // <<<< --- apply the default style
        vectorSource.addFeature( features[i] );
    }          

    var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
    });

As you can see I apply a default style to it. The default style must have some attribute based configuration like:

new ol.style.Style({
       fill: new ol.style.Fill({
           color: ${fillColor},
       }),
       stroke: new ol.style.Stroke({
           color: ${strokeColor},
           width: 1,
       })
});

This worked nice until OL2.

Now you say "Yo man, just use the style function function(feature, resolution) and use each feature attribute in the style! Bind it to the vectorLayer..."

Here comes the problem....

I have a default style because I need other styles to be applied to the features later. I have to switch styles between default and selected when the user clicks on each feature to hilight them.

var select = new ol.interaction.Select();
map.addInteraction(select);

select.on('select', function(event) {
    var selected = event.selected;
    var deselected = event.deselected;

    selected.forEach(function(feature){
          feature.setStyle( selectedStyle );
    });

    deselected.forEach(function(feature){
          feature.setStyle( defaultStyle );
    });                

});

I need to keep both styles dynamic because I'll not use the styles function anymore until I reload the entire layer.

I think removing the "${attribute_name}" dynamic value was a step back from the OL guys...

How can I do what I need?

Your Answer

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

Browse other questions tagged or ask your own question.