Get the distance between two geo points

后端 未结 9 593
旧巷少年郎
旧巷少年郎 2020-11-27 09:11

I want to make an app which checks the nearest place where a user is. I can easily get the location of the user and I have already a list of places with latitude and longitu

9条回答
  •  [愿得一人]
    2020-11-27 09:46

    a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)

    c = 2 ⋅ atan2( √a, √(1−a) )

    distance = R ⋅ c

    where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);

    note that angles need to be in radians to pass to trig functions!

    fun distanceInMeter(firstLocation: Location, secondLocation: Location): Double {
        val earthRadius = 6371000.0
        val deltaLatitudeDegree = (firstLocation.latitude - secondLocation.latitude) * Math.PI / 180f
        val deltaLongitudeDegree = (firstLocation.longitude - secondLocation.longitude) * Math.PI / 180f
        val a = sin(deltaLatitudeDegree / 2).pow(2) +
                cos(firstLocation.latitude * Math.PI / 180f) * cos(secondLocation.latitude * Math.PI / 180f) *
                sin(deltaLongitudeDegree / 2).pow(2)
        val c = 2f * atan2(sqrt(a), sqrt(1 - a))
        return earthRadius * c
    }
    
    
    data class Location(val latitude: Double, val longitude: Double)
    

提交回复
热议问题