Calculate distance between 2 GPS coordinates

前端 未结 29 3476
青春惊慌失措
青春惊慌失措 2020-11-21 23:34

How do I calculate distance between two GPS coordinates (using latitude and longitude)?

29条回答
  •  隐瞒了意图╮
    2020-11-22 00:06

    Here's a Kotlin variation:

    import kotlin.math.*
    
    class HaversineAlgorithm {
    
        companion object {
            private const val MEAN_EARTH_RADIUS = 6371.0
            private const val D2R = Math.PI / 180.0
        }
    
        private fun haversineInKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
            val lonDiff = (lon2 - lon1) * D2R
            val latDiff = (lat2 - lat1) * D2R
            val latSin = sin(latDiff / 2.0)
            val lonSin = sin(lonDiff / 2.0)
            val a = latSin * latSin + (cos(lat1 * D2R) * cos(lat2 * D2R) * lonSin * lonSin)
            val c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
            return EQATORIAL_EARTH_RADIUS * c
        }
    }
    

提交回复
热议问题