项目场景:
项目相关背景:公司一个项目里利用高德开发地图遇到的一个小难题
项目场景:给予高德开发地图,自定义绘制区域,绘制好区域后,可以根据客户输入的阔张数字绘制的区域进行相应的变化下面直接上代码
首先需要自己去高德地图Api官网注册自己的Key
1.引入或者 这个方法
// 使用这个绘制出想要的区域
var mouseTool = new AMap.MouseTool(map);
//监听draw事件可获取画好的覆盖物
var overlays = [];
mouseTool.on('draw',function(e){
console.log(e.obj._opts,'e.obj')
overlays.push(e.obj);
})
重点:如何计算出扩大之后的经纬度
function jiSuanJWD (){
// 测试点位
const originalCoordinates = [
[116.405, 39.905],
[116.41, 39.908],
[116.415, 39.905],
[116.418, 39.903],
[116.415, 39.9],
]
// 计算不规则区域的中心点
const centerPoint = originalCoordinates.reduce(
(acc, cur) => {
return [acc[0] + cur[0], acc[1] + cur[1]]
},
[0, 0]
)
centerPoint[0] /= originalCoordinates.length
centerPoint[1] /= originalCoordinates.length
// 定义扩张距离(单位:米)
const expansionDistance = 1
// 计算扩张后的坐标
const expandedCoordinates = originalCoordinates.map((coordinate) => {
// 计算方向
const direction = Math.atan2(coordinate[1] - centerPoint[1], coordinate[0] - centerPoint[0])
// 根据方向和扩张距离计算新的坐标点
const expandedLng = coordinate[0] + (Math.cos(direction) * expansionDistance) / (111 * Math.cos((coordinate[1] * Math.PI) / 180))
const expandedLat = coordinate[1] + (Math.sin(direction) * expansionDistance) / 111
return [expandedLng, expandedLat]
})
console.log(expandedCoordinates, originalCoordinates)}
1.首先定义了一个变量centerPoint
,用来存储原始坐标数组originalCoordinates
中所有坐标的和。初始值为[0, 0]。
2.使用reduce
方法对originalCoordinates
数组进行遍历,将每个坐标的x和y分量分别累加到centerPoint
中。
3.接着,将centerPoint
中的x和y分量分别除以originalCoordinates
数组的长度,得到中心点的坐标。
4.定义了一个变量expansionDistance
,表示扩张距离,单位为米。
5.使用map方法对originalCoordinates
数组进行遍历,对每个坐标进行扩张操作。
6.首先计算当前坐标与中心点之间的方向,使用Math.atan2
函数计算方向角度。
7.根据方向角度和扩张距离,计算新的经度(expandedLng)
和纬度(expandedLat)
。
8.将新的经度和纬度组成一个新的坐标,并将其添加到expandedCoordinates
数组中。
9.最后,打印输出扩张后的坐标数组(expandedCoordinates
)和原始坐标数组(originalCoordinates
)。