Search code examples
openlayersopenlayers-5

Styling GeoJSON by filters in OpenLayers


I'm trying to style a GeoJSON based on a layer's classification by classes. I'm trying to do it using the method of the greaterThan type filters etc ... This would be more or less how I'd like to classify the GeoJSON.

enter image description here

I did the following, initially, I wanted to test with just one interval to see if it worked.

//style
var individuals = new ol.style.Style({
    symbolizers: [
      new ol.style.Stroke({color: '#000000', width: 1}),
      new ol.style.Fill({color: '#ff0000'})
    ],
    filter:ol.format.filter.greaterThan(
        ol.format.filter.GreaterThanOrEqualTo('individuals', '0'),
        ol.format.filter.LessThanOrEqualTo('individuals', '500')
    )
});

//vecLayer
var vectorDistribution = new ol.source.Vector({
    url: 'data/distribution.json',
    projection: 'EPSG:4326',
    format: new ol.format.GeoJSON(),
    
});

var distribution = new ol.layer.Vector({    
    name: 'Distribution',
    source: vectorDistribution,
    visible:true,
    displayInLayerSwitcher: false,
    style: individuo,
    maxZoom:7,
    //minResolution: 200,
    //maxResolution: 2000,
});

Well, it does not symbolize, Someone did something similar and can help me.


Solution

  • ol.style.Style does not have symbolizers or filter properties, you may be confusing it with OpenLayers 2 styles. In OpenLayers 6 if you want to fill a polygon with a color based on the value of a property you can use a style function, for example

    var style = new ol.style.Style({
        stroke: new ol.style.Stroke({color: '#000000', width: 1}),
        fill: new ol.style.Fill()
    });
    
    var individuals = function(feature) {
        var value = feature.get('individuals');
        var color = value <  115 ? '#ffffff' :
                    value <  360 ? '#ff7f7f' :
                    value <  570 ? '#ff3f3f' :
                    value <  850 ? '#ff0000' :
                    value < 1600 ? '#7f0000' : '#3f0000';
        style.getFill().setColor(color);
        return style;
    };