18034727885
2026-04-14 370014cbb9ec1ef64e7e42bb4f9a12671461d8e4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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()
    }
}