lee
lee

Reputation: 772

Open Street Maps, and callback for OpenLayer

I have a map from olms and I'm trying to overlay a 4x4 grid on it. I want the square being hovered to change color. This code is somewhat working, but it's not consistent, and is prone to error at times. How do I make this more consistent?

This is my mouse move callback:

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

And this is where I set it:

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

Upvotes: 1

Views: 162

Answers (1)

Mike
Mike

Reputation: 17962

Because you have more than one vector layer you will need to use a filter in forEachFeatureAtPixel

  var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
    return feature;
  },{
    layerFilter: function(candidate) {
      return candidate === polyLayer
    }
  });

Upvotes: 1

Related Questions