【问题标题】:leaflet.js ImageOverlay zoom changes marker positionLeaflet.js ImageOverlay 缩放更改标记位置
【发布时间】:2026-01-15 07:25:01
【问题描述】:

我正在使用 ImageOverlay 将图像用作地图,使用 Leaflet.js - 但是在更改缩放时,标记会更改位置。

已遵循此tutorial 中的指导,代码笔示例为here

// Markers 
var markers = [{"title":"OneOcean Port Vell","description":"Super yacht marina","link":"http:\/\/www.oneoceanportvell.com\/","x":"68.28125","y":"68.443002780352178"}]; 

var map = L.map('image-map', {
  minZoom: 2,
  maxZoom: 4,
  center: [0, 0],
  zoom: 2,
  attributionControl: false,
  maxBoundsViscosity: 1.0,
  crs: L.CRS.Simple
});

// dimensions of the image
var w = 3840,
    h = 2159,
    url = 'map.png';

// calculate the edges of the image, in coordinate space
var southWest = map.unproject([0, h], map.getMaxZoom()-1);
var northEast = map.unproject([w, 0], map.getMaxZoom()-1);
var bounds = new L.LatLngBounds(southWest, northEast);

// add the image overlay, 
// so that it covers the entire map
L.imageOverlay(url, bounds).addTo(map);

// tell leaflet that the map is exactly as big as the image
map.setMaxBounds(bounds);

// Add Markers  
for (var i = 0; i < markers.length; i++){
    var marker = markers[i];

    // Convert Percentage position to point
    x = (marker['x']/100)*w;
    y = (marker['y']/100)*h;

    point = L.point((x / 2), (y / 2))
    latlng = map.unproject(point);

    L.marker(latlng).addTo(map);
}

在 codepen 中,将 zoom 更改为 4 以查看标记丢失位置。

理想情况下,我会尝试更改缩放以适应不同的屏幕尺寸并让更多地图在移动设备上可见。

也可能相关,我看不到让zoomSnap 功能工作以允许小数缩放。

任何指针都非常受欢迎。

【问题讨论】:

  • 你知道你应该提供足够的代码来在你的问题的body中创建一个MCVE,而不是仅仅依赖外部服务。
  • 如果您需要zoomSnap 的帮助,请打开一个新问题。
  • @ghybs 道歉 - 已编辑问题以添加准系统示例。
  • @ghybs - 感谢您的帮助,让 zoomSnap 正常工作 - 只需要 zoomDelta 以及缩放控件也是小数。

标签: javascript leaflet zooming


【解决方案1】:

map.unproject 需要 zoom 值,您希望在该值处应用非投影。

在计算boundscenter 时,您正确地将静态imageZoom 值指定为unproject,但不适用于标记位置。

如果未指定 zoom 参数,则 unproject 使用当前地图缩放级别,即您在 zoom 变量中定义的级别。这就是为什么当您更改其值时,标记的unproject 使用不同的值,并且它们位于不同的位置。

您甚至不得不将您的 xy 值(相对于您的图像)除以 2,以说明在您的初始情况下,它们对于 4 的 imageZoom 是正确的,但由于你没有为unproject指定缩放,后者使用当前的zoom(即3),所以坐标应该除以2才能“正确”。

更新代码笔:https://codepen.io/anon/pen/pLvbvv

【讨论】: