前情提要:工作上遇到一个需要在地图画圆圈的需求,是在别人的低代码平台开发,不是高德,百度、腾讯地图....平台没有直接画圆的方法,只提供一个画折现的方法,于是通过计算圆周的坐标点利用画折现的方法实现。
代码如下:
generateCirclePoints(centerLat, centerLon, radiusInMeters, numberOfPoints) {
const earthRadius = 6371000 // 地球半径,单位为米
const points = []
const step = 360 / numberOfPoints // 每个点的角度间隔
const radiusInDegrees = radiusInMeters / ((earthRadius * Math.PI) / 180.0) // 将米转换为纬度/经度差的角度
const centerLatRad = (centerLat * Math.PI) / 180.0 // 中心点纬度转换为弧度
const centerLonRad = (centerLon * Math.PI) / 180.0 // 中心点经度转换为弧度
for (let angle = 0; angle < 360; angle += step) {
const angleRad = (angle * Math.PI) / 180.0 // 角度转换为弧度
const latRad = Math.asin(
Math.sin(centerLatRad) * Math.cos(radiusInDegrees) +
Math.cos(centerLatRad) * Math.sin(radiusInDegrees) * Math.cos(angleRad),
)
const lonDiffRad = Math.atan2(
Math.sin(angleRad) * Math.sin(radiusInDegrees) * Math.cos(centerLatRad),
Math.cos(radiusInDegrees) - Math.sin(centerLatRad) * Math.sin(latRad),
)
const newLonRad = centerLonRad + lonDiffRad
const newLat = (latRad * 180) / Math.PI // 纬度转换为度
const newLon = (newLonRad * 180) / Math.PI // 经度转换为度
points.push([newLat, newLon])
}
return points
},
return points
},
numberOfPoints这个参数设置越大,圆圈画出来越圆