打开街道地图,并回调 OpenLayer

Open Street Maps, and callback for OpenLayer

我有一张来自 olms 的地图,我正在尝试在其上叠加一个 4x4 网格。我希望悬停的正方形改变颜色。 This code 有点工作,但它不一致,有时容易出错。我如何使它更一致?

这是我的鼠标移动回调:

var displayFeatureInfo = function(pixel) {
  var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
    return feature;
  });

  if (feature) {
    document.body.style.cursor = 'pointer';
  } else {
    document.body.style.cursor = 'default';
  }

  if (feature !== highlight) {
    if (highlight) {
      featureOverlay.getSource().removeFeature(highlight);
    }
    if (feature) {
      featureOverlay.getSource().addFeature(feature);
    }
    highlight = feature;
  }
}

这是我设置的地方:

olms('map', 'https://maps.tilehosting.com/styles/darkmatter/style.json?key=' + apiKey).then(function(mp) {
  map = mp;
  map.setView(view);
  map.addLayer(polyLayer);
  featureOverlay = new VectorLayer({
    source: new VectorSource(),
    map: map,
    style: function(feature) {
      return highlightStyle;
    }
  });
  map.on('pointermove', function(evt) {
    if (evt.dragging) {
      return;
    }
    var pixel = map.getEventPixel(evt.originalEvent);
    displayFeatureInfo(pixel);
  });
});

因为你有不止一个矢量图层你需要在forEachFeatureAtPixel

中使用一个过滤器
  var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
    return feature;
  },{
    layerFilter: function(candidate) {
      return candidate === polyLayer
    }
  });