Calculate distance between 2 GPS coordinates

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

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

29条回答
  •  无人及你
    2020-11-21 23:55

    here is the Swift implementation from the answer

    func degreesToRadians(degrees: Double) -> Double {
        return degrees * Double.pi / 180
    }
    
    func distanceInKmBetweenEarthCoordinates(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Double {
    
        let earthRadiusKm: Double = 6371
    
        let dLat = degreesToRadians(degrees: lat2 - lat1)
        let dLon = degreesToRadians(degrees: lon2 - lon1)
    
        let lat1 = degreesToRadians(degrees: lat1)
        let lat2 = degreesToRadians(degrees: lat2)
    
        let a = sin(dLat/2) * sin(dLat/2) +
        sin(dLon/2) * sin(dLon/2) * cos(lat1) * cos(lat2)
        let c = 2 * atan2(sqrt(a), sqrt(1 - a))
        return earthRadiusKm * c
    }
    

提交回复
热议问题