[GIS] How to filter a vector layer in openlayers

filteropenlayerstypescript

I'm using openlayers (v3.20.0) in an angular 2 project.
I have a vector layer which has its source bound to a geoserver.

My task is to filter the features displayed in this layer. I have a collection Ids (which are in features' attributes) representing the features needed to be shown.
But I can't find how to filter the layer. There seems to have been an easy way to do this in openlayers v2, but not in v3.

What am I missing ?

Best Answer

If you want to filter the features on client side, the style parameter of your layer should be defined as style function. In the style function you filter the features and return a valid or a empty style depending if features with that id want to be shown.

Assuming you have the ids you want to show in an array called collectionList, you could do it like that:

var styleFunction = function(feature, resolution) {
    var style = new ol.style.Style({});
    var id = feature.get('collection_id');
    if (id && collectionList.includes(id) {
        style = new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: #000,
                width: 1
            })
        });
    }
    return style;
}