Leaflet将弹出窗口和标记居中显示在地图上

29

我希望在弹出窗口打开时将标记居中..并将地图居中,而不是在标记的经纬度上进行居中,但要在标记和弹出窗口的中心位置居中!

问题在于弹出窗口具有动态内容(在单击时加载)。

地图在移动设备上的尺寸为全屏显示大小! 我只是在弹出窗口中使用了autoPanPadding选项,但这还不够。

请参考以下图片:

popup centered in leaflet map

5个回答

59

使用fitzpaddy的答案,我能够编写出这段代码,它可以工作,并且更加灵活。

map.on('popupopen', function(e) {
    var px = map.project(e.target._popup._latlng); // find the pixel location on the map where the popup anchor is
    px.y -= e.target._popup._container.clientHeight/2; // find the height of the popup container, divide by 2, subtract from the Y axis of marker location
    map.panTo(map.unproject(px),{animate: true}); // pan to new center
});

我已经寻找这个解决方案很长时间了!谢谢你! - rafaels88
我根据这个答案,只使用公共属性和方法添加了一个新的回复,顺便说一句 :) - rafaels88

8

你好,Stefano:

这是未经测试的伪代码,但是 Leaflet 的 project/unproject 函数应该能够提供帮助。

例如:

// Obtain latlng from mouse event
var latlng;
// Convert latlng to pixels
var px = project(latlng);
// Add pixel height offset to converted pixels (screen origin is top left)
px.y -= mypopup.height/2
// Convert back to coordinates
latlng = unproject(px);
// Pan map
map.panTo(latlng,{animate: true});

这取决于在计算过程中缩放比例保持恒定,因此您可能需要平移地图,然后计算平移偏移量以正确更新(使用动画,这将只是一个轻柔的过渡)。
祝好运!

6

这里有一个简单的解决方案:

首先将地图居中到您的标记处。

map.setView(marker.latLng);

然后您打开弹出窗口。
var popup.openOn(map); = L.popup()
    .setLatLng(marker.latLng)
    .setContent(dynamic-content)
    .openOn(map);

Leaflet会自动平移地图,以适应弹出框的大小。为了使其更美观,您可以使用CSS向弹出框添加margin-top属性。

非常感谢!一直在寻找像这样的自动答案。其他计算弹出高度的答案对我没有用。 - Chris Dolphin
这个解决方案的问题在于它没有将弹出窗口和标记居中。它只会确保弹出窗口在可见地图内。 - Dan Mandle
@DanMandle 我认为如果你在CSS中添加top: 50%; translate: transformY(-50%);,它实际上会位于地图的中心。 - Titsjmen

0
我利用公共方法对@dan-mandle的回答进行了重构,因为他的回答(正确答案)使用了许多私有属性,这不是最佳实践。
    map.on("popupopen", (event) => {
      const popupPixelCoords = map.project(event.popup.getLatLng());
      const popupHeight = event.popup.getElement().clientHeight;
      popupPixelCoords.y -= popupHeight / 2; // move the popup vertical axis location down (distance: half of popup height)
      map.panTo(map.unproject(popupPixelCoords), { animate: true }); // pan to calculated location
    });

0

我的非常简单的解决方案还保持了当前的缩放级别,以提高可用性。

map.on('popupopen', function (e) {
    map.setView(e.target._popup._latlng, e.target._zoom);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接