MoreScratch
MoreScratch

Reputation: 3083

Styling features based on attribute values

How does one style features based on attributes/properties? Currently I am doing the following:

olLayer = new ol.layer.Vector( {
  source: new ol.source.Vector( {
    features: featureArray
  } ),
  style: ( function() {

    var styleR3 = new ol.style.Style( {
      image: new ol.style.Circle( {
        radius: 10,
        fill: new ol.style.Fill( {
          color: 'blue'
        } )
      } )
    } );

    var styleCatchAll = new ol.style.Style( {
      image: new ol.style.Circle( {
        radius: 5,
        fill: new ol.style.Fill( {
          color: 'red'
        } )
      } )
    } );

    return function( feature, resolution ) {
      if ( feature.attributes[ "Rank" ] === "3" ) {
        return styleR3;
      } else {
        return styleCatchAll;
      }
    };

  }() )
} );

The select features does work but the styleR3 does not get applied.

Upvotes: 2

Views: 4418

Answers (1)

Jonatas Walker
Jonatas Walker

Reputation: 14150

Here it is ... http://jsfiddle.net/jonataswalker/g3s96auc/

The style function requires an array on return, and you are using a self execution function, I don't know if this works, anyway, the style function became:

style: function(feature, resolution){
    var styleR3 = new ol.style.Style( {
        image: new ol.style.Circle( {
            radius: 10,
            fill: new ol.style.Fill( {
                color: 'blue'
            } )
        } )
    } );

    var styleCatchAll = new ol.style.Style( {
        image: new ol.style.Circle( {
            radius: 5,
            fill: new ol.style.Fill( {
                color: 'red'
            } )
        } )
    } );

    if ( feature.get('rank') == 3) {
        return [styleR3];
    } else {
        return [styleCatchAll];
    }
}

Upvotes: 6

Related Questions