How to filter layers using forEachFeatureAtPixel method
Asked Answered
F

2

8

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

Fellini answered 5/4, 2018 at 11:16 Comment(0)
F
12

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

Fellini answered 5/4, 2018 at 12:26 Comment(0)
K
4

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

Keynes answered 14/4, 2020 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.