首页 > 解决方案 > 如何通过无限平移(OpenLayers)获取投影特征的坐标

问题描述

我正在创建一个弹出控件,用于在用户将鼠标移动到特定图层上的功能上时显示信息。我希望弹出窗口捕捉到特征的几何(点)而不使用鼠标位置的坐标。

问题是这在主要特征上效果很好,但是,当向左或向右平移一个地球旋转并将鼠标悬停在投影特征上时,弹出窗口会在原始坐标处越过主要特征,而不是在扩展的平移视图。

这是我的代码:

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

我相信这个问题与使用有关,feature.getGeometry().getCoordinates()因为它只返回实际特征的坐标,而不是投影的坐标。有没有办法返回投影特征几何位置的像素坐标?

标签: openlayersopenlayers-3openlayers-5

解决方案


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

试试这个。


推荐阅读