Skip to content
Advertisement

Filter features with properties in OpenLayers

I’d like to filter features on the map using the feature properties.

For example if I have this property in the geojson:

...
"properties": {
                "Start": 10
            }
...

And I want to see only featuers with Start > 10, how can I implement that features with Start < 10 are hidden?

If I change the style with following code the features are transparent but they are still available after click if I use forEachFeatureAtPixel. I want that features are not displayed and there are not available for clicking etc.

let invisibleStyle = new ol.style.Fill({
    color: [0,0, 0, 0],
});

const NewLayer= new ol.layer.VectorImage ({
        source: new ol.source.Vector({
            url: *url*,
            format: new ol.format.GeoJSON(),
        }),
        visible: true,
        style: function (feature) {
        if (feature.get('Start')>10) {
            let style = new ol.style.Style({
                fill: fillStyle,
                stroke: strokeStyle
            })
            return style;   
        } else {
            let style = new ol.style.Style({
                fill: invisibleStyle,
            })
            return style;   
        }   
    });
map.addLayer(NewLayer);

I tried also to use the visible like this but it doesn’t work:

const NewLayer= new ol.layer.VectorImage ({
        source: new ol.source.Vector({
            url: *url*,
            format: new ol.format.GeoJSON(),
        }),
        visible: function(feature) {
                 if (feature.get('Start')<10) {
                    return true;
                 } else {
                    return false;
                 }
          },
        style: new ol.style.Style({
              fill: fillStyle,
              stroke: strokeStyle,
              })      
    });
map.addLayer(NewLayer);

Advertisement

Answer

Transparent fill cannot be seen but is hit detected (so you can select a polygon by clicking inside it). To avoid display and hit detection simply don’t return a style

    style: function (feature) {
      if (feature.get('Start')>10) {
        let style = new ol.style.Style({
            fill: fillStyle,
            stroke: strokeStyle
        })
        return style;   
      }
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement