首先,要创建一个数组mapData.value(声明一下,我使用的是vue3,所以有.value),这个数组里面包含地图上,你想要在可视化区域展示的所有点位信息,也就是经纬度信息。数据大概就是这个样子的。
mapData.value = [{
lon:xxxx,
lat:xxxx
},{
lon:xxxx,
lat:xxxx
},{
lon:xxxx,
lat:xxxx
}]
然后就开始封装函数啦,这一步我们先封装计算边界框的函数calculateBounds,这个函数要传入你获取好数据的mapData.value数据。
// 计算边界框
const calculateBounds = points => {
if (points.length === 0) {
return null;
}
let bounds = {
minLat: points[0].lat,
maxLat: points[0].lat,
minLng: points[0].lng,
maxLng: points[0].lng
};
points.forEach(point => {
if (point.lat < bounds.minLat) bounds.minLat = point.lat;
if (point.lat > bounds.maxLat) bounds.maxLat = point.lat;
if (point.lng < bounds.minLng) bounds.minLng = point.lng;
if (point.lng > bounds.maxLng) bounds.maxLng = point.lng;
});
return bounds;
};
边界值我们拿到了,那接下来就到了重点了,封装函数getCenterAndZoom计算我们的中心点位置以及放大比例。
// 根据边界框计算中心点和缩放级别
const getCenterAndZoom = bounds => {
const center = {
lat: (bounds.minLat + bounds.maxLat) / 2,
lng: (bounds.minLng + bounds.maxLng) / 2
};
// 计算合适的缩放级别,这里提供一个简单的估算方式,具体的缩放级别计算可以根据实际需求调整
const latDiff = bounds.maxLat - bounds.minLat;
const lngDiff = bounds.maxLng - bounds.minLng;
const maxDiff = Math.max(latDiff, lngDiff);
let zoom = 12; // 初始缩放级别
if (maxDiff > 0) {
zoom = Math.floor(12 - Math.log(maxDiff) / Math.LN2); // 示例计算方式
}
zoom = Math.min(zoom, 21); // 确保缩放级别不超过最大值
zoom = Math.max(zoom, 1); // 确保缩放级别不小于最小值
return { center, zoom };
};
所用到的所有函数都封装好了,那么接下来就要开始用这个函数了。声明一下,我是在写leaflet的时候,没有找到类似于高德地图官方提供的setFitView()方法,我才自己手写的。废话不多说,下面是怎么调用的。
const bounds = calculateBounds(mapData.value);
if (bounds) {
const { center, zoom } = getCenterAndZoom(bounds);
map.value.centerAndZoom(new T.LngLat(center.lng, center.lat), zoom);
}
这几行代码,就是你在需要地图调整合适的缩放等级和中心点,以保证所有元素都显示其中时,都可以加上这几行代码。