leaflet.js ImageOverlay 缩放更改标记位置

leaflet.js ImageOverlay zoom changes marker position

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

已遵循此 tutorial and a code pen example is 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 功能可以进行小数缩放。

非常感谢任何指点。

map.unproject 需要您希望应用 un-projection 的 zoom 值。

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

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

您甚至必须将 xy 值(相对于您的图像)除以 2,以说明在您的初始情况下,它们对于 imageZoom of 4,但是由于你没有为unproject指定缩放,后者使用当前的zoom(即3),所以坐标应该除以2就是"correct" .

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