OpenLayers 3 hasFeatureAtPixel filter for layer

2019-07-24 03:27发布

I am attempting to create a mouse hover event using the following method taken from the official OL3 examples page:

http://openlayers.org/en/latest/examples/earthquake-clusters.html

I need to trigger the action only when hovering over a particular layer. Having consulted the official documentation I discovered that you can use a layer filter function with hasFeatureAtPixel, but it doesn't appear to be working.

map.on('pointermove', function(evt) {
    if (evt.dragging) {
       return;
    }
    var pixel = map.getEventPixel(evt.originalEvent);
    var hit = map.hasFeatureAtPixel(pixel, function(feature, layer) {
        console.log(layer);
        console.log(feature);       
    });
});

The console.log calls result in feature objects being given in the console, but no layer objects, these are returned as 'undefined'. It is the layer objects which I need to test whether the layer is the correct one.

Any ideas why this isn't working?

2条回答
闹够了就滚
2楼-- · 2019-07-24 04:23

The filter function will receive one argument, the layer-candidate and it should return a boolean value.

From API Docs.

Let's say you have a layer like:

var vectorLayer = new ol.layer.Vector({
  name: 'test',
  // ...
});

You can add a layer filter function like:

map.on('pointermove', function(e) {
  if (e.dragging) return;

  var hit = map.hasFeatureAtPixel(e.pixel, function(layer) {
    return layer.get('name') === 'test'; // boolean
  });
  map.getTarget().style.cursor = hit ? 'pointer' : '';
});
查看更多
Fickle 薄情
3楼-- · 2019-07-24 04:24

Actually the API is rewritten (v4.0.1), the working example is as follows:

var hit = map.hasFeatureAtPixel(e.pixel, {
    layerFilter: function (layer) {
        return layer.get('name') === 'test';
    }
});
查看更多
登录 后发表回答