Calculate distance between 2 GPS coordinates

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

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

29条回答
  •  难免孤独
    2020-11-22 00:06

    i took the top answer and used it in a Scala program

    import java.lang.Math.{atan2, cos, sin, sqrt}
    
    def latLonDistance(lat1: Double, lon1: Double)(lat2: Double, lon2: Double): Double = {
        val earthRadiusKm = 6371
        val dLat = (lat2 - lat1).toRadians
        val dLon = (lon2 - lon1).toRadians
        val latRad1 = lat1.toRadians
        val latRad2 = lat2.toRadians
    
        val a = sin(dLat / 2) * sin(dLat / 2) + sin(dLon / 2) * sin(dLon / 2) * cos(latRad1) * cos(latRad2)
        val c = 2 * atan2(sqrt(a), sqrt(1 - a))
        earthRadiusKm * c
    }
    

    i curried the function in order to be able to easily produce functions that have one of the two locations fixed and require only a pair of lat/lon to produce distance.

提交回复
热议问题