Search code examples
openlayersopenlayers-3openlayers-5

How to get coordinates of a projected feature with infinite panning (OpenLayers)


I am creating a popup control for displaying information when a user moves the mouse over a feature on a specific layer. I want the popup to snap to the geometry (point) of the feature and not use the coordinate of the mouse position.

The issue is that this works fine on the main feature, however, when panning one earth rotation to the left or right and hovering over a projected feature, the popup goes over the main feature at the original coordinates and not the feature that is in the extended panned view.

This is my code:

const container = document.getElementById('popup');
const content = document.getElementById('popup-content');

var popup = new ol.Overlay({
  element: container,
  positioning: "bottom-center",
  stopEvent: false
});

map.addOverlay(popup);

map.on("pointermove", function (e) {
  if (e.dragging) {
    popup.setPosition(undefined);
    return;
  }

  const feature = map.forEachFeatureAtPixel(e.pixel,
    function (feature, layer) {
      if (layer === participantLayer) {
        return feature;
        }
    }, { hitTolerance: 10 });

    if (feature) {
      popup.setPosition(feature.getGeometry().getCoordinates());
      content.innerHTML = "...";
    } else {
       popup.setPosition(undefined);
  }
});

I believe the issue has to do with using feature.getGeometry().getCoordinates() since it returns only the coordinates of the actual feature and not the projected ones. Is there a way to return pixel coordinates of the location of the projected feature's geometry?


Solution

  • let featureCoords = feature.getGeometry().getCoordinates();  
    const projWidth = ol.extent.getWidth(map.getView().getProjection().getExtent());  
    const worldsAway = Math.round(e.coordinate[0] / projWidth);  
    featureCoords[0] = featureCoords[0] + worldsAway * projWidth;  
    popup.setPosition(featureCoords);   
    

    Give this a try.