1

In my GeoJSON file, there is an attribute for each polygon. I am trying to update the fillcolor of the polygon base on the value of an attribute in the GeoJSON file. I have a function getColor() that returns a color, based on the input value.

There is already similar solution, but that was in 2012.

Can you help me?

Error("${getColor(ID)}"): Unexpected template string expression. (no-template-curly-in-string)

var styles = [
  new Style({
    stroke: new Stroke({
      color: "blue",
      width: 3
    }),
    fill: new Fill({
      color: "${getColor(ID)}"
    })
  },
  {
    context: 
    {

      getColor : function (feature) {
        return feature.attributes.ID > 950 ? '#800026' :
        feature.attributes.ID > 750 ? '#BD0026' :
        feature.attributes.ID > 500 ? '#E31A1C' :
        feature.attributes.ID > 250 ? '#FC4E2A' :
        feature.attributes.ID > 150 ? '#FD8D3C' :
        feature.attributes.ID > 50  ? '#FEB24C' :
        feature.attributes.ID > 10  ? '#FED976' :
        '#FFEDA0' ;
      }
    } 
  })
];
3

1 Answer 1

2

You should style the layer with a style function

var style = new Style({
  stroke: new Stroke({
    color: 'blue',
    width: 3
  }),
  fill: new Fill()
});

var styleFunction = function (feature) {
  var id = feature.getId();
  var color = 
    id > 950 ? '#800026' :
    id > 750 ? '#BD0026' :
    id > 500 ? '#E31A1C' :
    id > 250 ? '#FC4E2A' :
    id > 150 ? '#FD8D3C' :
    id > 50  ? '#FEB24C' :
    id > 10  ? '#FED976' :
               '#FFEDA0' ;
  style.getFill().setColor(color);
  return style;
};

Example here https://codesandbox.io/s/vector-esri-0vjwn

Feature do not have an attribute property. The feature id is accessed using getId() and other attributes using get('attribute-name')

4
  • how do I correctly take the "ID" values from a json file? here is my json
    – iskakdar
    May 7, 2020 at 10:44
  • { "type": "Feature", "properties": { "ID": 2, "begin": 11, "end": 20 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 46.00576, 58.08009 ], [ 46.00576, 58.11442 ], [ 45.85899, 58.1373 ], [ 45.56547, 58.12586 ], [ 45.51655, 58.08009 ], [ 45.51655, 58.04577 ], [ 45.76115, 58.02288 ], [ 45.81007, 58.02288 ], [ 45.85899, 58.03432 ], [ 46.00576, 58.02288 ], [ 46.00576, 58.08009 ] ] ] ] } },
    – iskakdar
    May 7, 2020 at 10:45
  • That is in the properties collection so is accessed in an OpenLayers feature using .get('ID')
    – Mike
    May 7, 2020 at 10:55
  • thank you very much, friend. You are the best! everything works!
    – iskakdar
    May 7, 2020 at 11:01

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.