package commons.gis import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.pow import kotlin.math.sin import kotlin.math.sqrt /**基础工具**/ object BasicTools { /** * 计算2点距离 * @return 返回米 * **/ fun calculateHaversineDistance(lng1: Double, lat1: Double, lng2: Double,lat2: Double): Double { val earthRadius = 6371000.0 // 地球半径,单位:米 val lat1 = Math.toRadians(lat1) val lon1 = Math.toRadians(lng1) val lat2 = Math.toRadians(lat2) val lon2 = Math.toRadians(lng2) val dlat = lat2 - lat1 val dlon = lon2 - lon1 val a = sin(dlat / 2).pow(2) + cos(lat1) * cos(lat2) * sin(dlon / 2).pow(2) val c = 2 * atan2(sqrt(a), sqrt(1 - a)) return earthRadius * c } /** * 根据两个坐标点计算航向角 * @param fromLon 起始点经度 * @param fromLat 起始点纬度 * @param toLon 终点经度 * @param toLat 终点纬度 * @return 航向角(度),范围 0-360 */ fun calculateBearing(fromLon: Double, fromLat: Double, toLon: Double, toLat: Double): Double { // 将度转换为弧度 val lat1 = Math.toRadians(fromLat) val lat2 = Math.toRadians(toLat) val deltaLon = Math.toRadians(toLon - fromLon) // 计算航向角 val y = sin(deltaLon) * cos(lat2) val x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(deltaLon) val bearing = Math.toDegrees(atan2(y, x)) // 确保航向角在 0-360 度范围内 return (bearing + 360) % 360 } }