package com.xw.common.utils import com.amap.api.maps.model.LatLng import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt /** * 线段距离计算器 * 基于高德地图的经纬度距离计算算法(Haversine公式) */ object CalculatorLineDistance { // 地球半径(米) private const val EARTH_RADIUS_METERS = 6378137.0 fun calculate(startPoint: LatLng, endPoint: LatLng): Float { return calculateHaversineDistance( startPoint.latitude, startPoint.longitude, endPoint.latitude, endPoint.longitude ) } /** * 使用Haversine公式计算球面两点间的距离 * 这是高德地图内部使用的算法实现 */ private fun calculateHaversineDistance( startLatitude: Double, startLongitude: Double, endLatitude: Double, endLongitude: Double ): Float { // 将角度转换为弧度 val startLatRad = Math.toRadians(startLatitude) val startLngRad = Math.toRadians(startLongitude) val endLatRad = Math.toRadians(endLatitude) val endLngRad = Math.toRadians(endLongitude) // 计算经纬度差值 val deltaLatitude = endLatRad - startLatRad val deltaLongitude = endLngRad - startLngRad // Haversine公式核心计算 val haversineA = sin(deltaLatitude / 2.0) * sin(deltaLatitude / 2.0) + cos(startLatRad) * cos(endLatRad) * sin(deltaLongitude / 2.0) * sin(deltaLongitude / 2.0) val centralAngle = 2.0 * atan2( sqrt(haversineA), sqrt(1.0 - haversineA) ) // 计算最终距离 val distance = EARTH_RADIUS_METERS * centralAngle return distance.toFloat() } }