Loading

js 计算两个地点坐标之间的间距

/**
 * 计算两个地点坐标之间的间距
 * @param {array} location1 [lon: string, lat: string] 地点坐标
 * @param {array} location2 [lon: string, lat: string] 地点坐标
 */
export function calculateDistance(location1, location2) {
	const earthRadius = 6371 // 地球半径,单位为千米

	function toRadians(degrees) {
		return degrees * (Math.PI / 180)
	}

	// 将经纬度转换为弧度
	const radLat1 = toRadians(location1[1])
	const radLon1 = toRadians(location1[0])
	const radLat2 = toRadians(location2[1])
	const radLon2 = toRadians(location2[0])

	// 计算经纬度差值(弧度)
	const diffLat = radLat2 - radLat1
	const diffLon = radLon2 - radLon1

	// 应用 Haversine 公式计算距离
	const a =
		Math.sin(diffLat / 2) * Math.sin(diffLat / 2) +
		Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(diffLon / 2) * Math.sin(diffLon / 2)
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
	return earthRadius * c
}
posted @ 2023-11-14 14:40  Frank-Link  阅读(355)  评论(0编辑  收藏  举报