leafLet地图自适应,需要地图调整合适的缩放等级和中心点,以保证所有元素都显示,类似于高德地图的setFitView(),适用于所有地图。

首先,要创建一个数组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计算我们的中心点位置以及放大比例。

<
转载请说明出处内容投诉
CSS教程网 » leafLet地图自适应,需要地图调整合适的缩放等级和中心点,以保证所有元素都显示,类似于高德地图的setFitView(),适用于所有地图。

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买