OpenLayers 3 hasFeatureAtPixel filter for layer

佐手、 提交于 2019-12-11 04:22:23

问题


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?


回答1:


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' : '';
});



回答2:


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';
    }
});


来源:https://stackoverflow.com/questions/39354438/openlayers-3-hasfeatureatpixel-filter-for-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!