This question is old but I was looking for a similar solution and found one. I am using OpenLayers v5+ and Angular 6, but this shouldn't make a difference for older versions, the idea is the same regardless of the versions.
What you can do is define 2 layers, one hidden and one visible with styling. You can then load your data into the hidden layer. When the user triggers a filter action, you take the filter parameters and select the appropriate features from the source of the hidden layer, collect them and add them to the source of the visible layer.
The following code demonstrates the idea, is simplified and should be adjusted to the used version and language(JavaScript/TypeScript).
export class MyGeoApp implements OnInit {
private map = new Map();
private hiddenSource = new VectorSource();
private hiddenLayer = new VectorLayer({
source: this.hiddenSource,
visible: false
});
private visibleSource = new VectorSource();
private visibleLayer = new VectorLayer({
source: this.visibleSource,
visible: true
});
constructor() { }
ngOnInit() {
this.map.addLayer(this.hiddenLayer);
this.map.addLayer(this.visibleLayer);
this.loadData();
}
loadData() {
// load data in your hiddenSource
}
updateVisibleLayer(filterCriteria) {
// Clear the source before adding data
this.visibleSource.clear();
// Your filter
const myFilter = (query) => {
return this.hiddenSource.getFeatures()
.filter(feature =>
feature.get('country').toLowerCase()
.indexOf(query.toLowerCase()) > -1
);
// Add the features to your visible layer, using myFilter
this.visibleSource.addFeatures(myFilter(filterCriteria));
}
}
I am assuming you know how to load your data into the hiddenSource
. The example above can be applied to any type of user based selection, e.g.: a drop down list, checkbox, radio button, link, etc.
The filtering is based on the fact that the method getFeatures()
returns an Array
of Feature
objects. Arrays have many methods to use and one of them is the filter()
method. Check this link for more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter