Search code examples
javascriptgisopenlayersopenlayers-3

How to filter layers using forEachFeatureAtPixel method


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


Solution

  • 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 :)