I'm having hard time figuring out how to filter layers using forEachFeatureAtPixel method. I was going trough documentation but without any success so far. I basically want to filter layers and apply overlay style on event (for example "click") or to be more precise I want to implement hover effect using this example but with isolated layer.
In example above is used like this to get feature:
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
I wanted to tweak code a bit by using layer filter but I got syntax Uncaught SyntaxError: Unexpected token (
syntax error:
var features = map.getFeaturesAtPixel(pixel, function(features) {
layerFilter: function(layer) {
return layer.get('layer_name') === 'someName';
}
});
Then, I tried like this
var feature = map.forEachFeatureAtPixel(pixel, {
layerFilter: function(layer) {
return layer.get('layer_name') === 'someName';
}
});
but then I got Uncaught TypeError: d.call is not a function
error
I'm using documentation but to be fair I'm kind of struggling with reading and implementing some of the methods API
Ok, I finally did it. I was a bit hasty while reading documentation, problem was in callback function. I needed to return feature as it is pointed out in documentation. ...To stop detection, callback functions can return a truthy value.
So, proper formatting is like this: (I'm using 4.5.6 version)
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
}, {
layerFilter: function(layer) {
return layer.get('layer_name') === 'someName';
}
});
Now is working properly. Enjoy :)
For those who suffered like me with layer names I can suggest you that below way as an alternative;
I have stored my all layers in variables then filter them like this;
var countryLayer = new VectorLayer({
source: countryLayerSource,
style: //some styling in here
});
...
var feature = map.forEachFeatureAtPixel(
pixel,
function (feature) {
return feature;
},
{
layerFilter: function (layer) {
return layer === countryLayer;
},
}
);
Used API: v6.3.1. Openlayers API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With