0


高德API JS 高德地图获取多个坐标点的中心点

高德API JS 高德地图获取多个坐标点的中心点

一、需求

我需要在地图上展示多个地点,并且展示的同时,地图缩放到合适的大小,要求刚好能显示全部点位,并且边缘留有一部分间隔。
做成如图所示这样。
在这里插入图片描述

在这里插入图片描述

二、需要用到的 AMap 类库

经过一下午的研究,弄出来了。

需要以下这些 AMap 的类库:

  • AMap.Bounds() 区域
  • AMap.LngLat() 点坐标(基础点位)
  • AMap.setBounds() 设置地图区域,这会自动移动地图画面到这个区域中

高德地图 API Bounds 的官方文档:
https://lbs.amap.com/api/javascript-api-v2/documentation#bounds

在这里插入图片描述

三、实现

比如有这样一个点位数组,需要按上面的要求显示到地图中

[{"name":"大明湖","position":[117.023666,36.67672],"note":"","type":"","img":""},{"name":"济南五龙潭","position":[117.014772,36.665984],"note":"","type":"","img":""},{"name":"济南高新万达","position":[117.128471,36.686068],"note":"","type":"","img":""},{"name":"济南宜家","position":[116.928408,36.663449],"note":"","type":"","img":""},{"name":"济南华山风景区","position":[117.070015,36.728507],"note":"","type":"","img":""}]

1. 获取这些点中的最值

描述一个区域需要这个区域的对角线上的两个点的坐标值。
我们需要找出这些点的最值。

我写了个方法

/**
 * 获取区域对角线的两点坐标,即这个区域内的最小坐标值和最大坐标值
 *
 * @param pointerArray [[a,b],[c,d]]
 * @return Array {min:number[a,b], max:number[c,d]}
 */getMaxBoundsPointer(pointerArray){let lngArray = pointerArray.map(item=> item[0])let latArray = pointerArray.map(item=> item[1])return{min:[Math.min(...lngArray),  Math.min(...latArray)],max:[Math.max(...lngArray),  Math.max(...latArray)],}},

它接收的是这些点位的数组,格式是

[[a,b],[c,d]]

,如下即可。

let maxLocations =this.getMaxBoundsPointer(pointer.pointerArray.map(item=> item.position))

获取到的结果如下:

在这里插入图片描述

2. 计算合适的地图边界距离

当显示这些点的时候,如果你使用上面的区域,就会发现有些点跑到了地图的最边缘。而这不是我们想要的,所以需要给它加一个边界值。
而合适的边界距离并不是一个定值,因为这些点的距离是不定的,以上只是一个点位组合的展示,而我还需要展示其它点位组合,这些组合的间隔可能会更大。

所以我们需要用计算出来的

maxLocations

来计算这个区域的长宽值,然后再取它的

1/4

作为边界,显示的就会比较合理。

// 取区间的 1/4 作为地图的边界let lngGap =(maxLocations.max[0]- maxLocations.min[0])/4let latGap =(maxLocations.max[1]- maxLocations.min[1])/4

3. 计算新的区域值

新的区域值需要在原来极点坐标的基础之上加上前一步计算出来的边界值。

// 新的区域极点坐标let min =newAMap.LngLat(maxLocations.min[0]- lngGap, maxLocations.min[1]- latGap)let max =newAMap.LngLat(maxLocations.max[0]+ lngGap, maxLocations.max[1]+ latGap)

4. 设置地图的 Bounds

设置地图的 Bounds。

  1. 当点位数组数量多于一个点时,就按上面的方法获取区域值,并设置它 AMap.setBounds()
  2. 当点位数组数量是一个点时,就把这个点作为地图的中心点,通过 AMap.setCenter() 来设置中心点
  3. 当点位数量为 0 时,不处理
// 1. 多个点时,设置 boundsif(pointer.pointerArray.length >1){let bounds =newAMap.Bounds(min, max)this.map.setBounds(bounds)}// 2. 一个点时,将其作为中心点elseif(pointer.pointerArray.length ===1){
    console.log(pointer.pointerArray)let centerLngLat =newAMap.LngLat(...pointer.pointerArray[0].position)this.map.setCenter(centerLngLat)// 设置地图中心点坐标}// 3.else{}

完活儿

https://kylebing.cn/tools/map

标签: 高德

本文转载自: https://blog.csdn.net/KimBing/article/details/130991747
版权归原作者 十月ooOO 所有, 如有侵权,请联系我们删除。

“高德API JS 高德地图获取多个坐标点的中心点”的评论:

还没有评论