我有五个标记:一个用于中心(坐标:0,0),四个用于每一侧,坐标为: (1, 1) (1, -1) (-1, 1) (-1, -1) 我正在尝试调整地图以在中心显示所有标记。
我的做法是这样的:
const locations = [
{latitude: 1, longitude: 1},
{latitude: 1, longitude: -1},
{latitude: -1, longitude: 1},
{latitude: -1, longitude: -1},
]
const markers = []
for (let location of locations) {
markers.push(createMarker([location.latitude, location.longitude))
}
if (markers.length) {
const group = new L.featureGroup(markers)
map.fitBounds(group.getBounds(), paddings: [20, 20])
}
地图现在不居中。当我控制台记录以下内容时:
console.log(map.getBounds())
我得到:
{
_northEast: {
lat: 0.34332069940055443,
lng: 0.45867919921875006
},
_southWest: {
lat: -0.34332069940055443,
lng: -0.45593261718750006
}
}
这是结果:
为什么不居中?
假设
createMarker
正在创建一个 L.marker
实例。默认图标大小为 25x41 像素。因此填充应至少为 41 像素。
您的代码中也有一些拼写错误。拼写错误之一是
paddings
应该是单数:padding
。
const map = L.map('map')
.setView([46.801111, 8.226667], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
// make sure that OpenStreetMap is linked, skipped here due to line width
attribution: '© OpenStreetMap'
}).addTo(map);
function createMarker(latlng) { // assuming a simple marker
return L.marker(latlng).addTo(map);
}
const locations = [
{latitude: 1, longitude: 1},
{latitude: 1, longitude: -1},
{latitude: -1, longitude: 1},
{latitude: -1, longitude: -1},
]
const markers = [];
for (let location of locations) {
markers.push(
createMarker([location.latitude, location.longitude])
);
}
if (markers.length) {
const group = new L.featureGroup(markers);
map.fitBounds(group.getBounds(), {
// default icon size is 25x41 pixels
padding: [45, 45]
});
}
当
padding: [45, 45]
时,虽然这些点与地图边界的距离相同,但标记不会显示在中心位置。您可以使用 paddingTopLeft
和 paddingBottomRight
代替:
map.fitBounds(group.getBounds(), {
paddingTopLeft: [45, 45],
paddingBottomRight: [4, 4]
});
您可以通过调用获取图标大小(如果您使用其他标记):
console.log(markers[0].getIcon().options.iconSize);
zoomSnap
:
const map = L.map('map', { zoomSnap: 0.2 })
.setView([46.801111, 8.226667], 13);