Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 506
Svinjica Avatar asked Apr 05 '18 11:04

Svinjica


2 Answers

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

like image 176
Svinjica Avatar answered Oct 13 '22 13:10

Svinjica


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

like image 44
Ardahan Kisbet Avatar answered Oct 13 '22 11:10

Ardahan Kisbet