How to calculate the distance between two GPS coordinates without using Google Maps API?

前端 未结 7 1116
小鲜肉
小鲜肉 2020-12-08 02:56

I\'m wondering if there\'s a way to calculate the distance of two GPS coordinates without relying on Google Maps API.

My app may receive the coordinates in float or

7条回答
  •  温柔的废话
    2020-12-08 03:05

    Converted the accepted answer to Swift 3.1 (works on Xcode 8.3), in case anyone needs it:

    public static func calculateDistanceMeters(departure: CLLocationCoordinate2D, arrival: CLLocationCoordinate2D) -> Double {
    
        let rad_per_deg = Double.pi / 180.0 // PI / 180
        let rkm = 6371.0                    // Earth radius in kilometers
        let rm = rkm * 1000.0               // Radius in meters
    
        let dlat_rad = (arrival.latitude - departure.latitude) * rad_per_deg // Delta, converted to rad
        let dlon_rad = (arrival.longitude - departure.longitude) * rad_per_deg
    
        let lat1_rad = departure.latitude * rad_per_deg
        let lat2_rad = arrival.latitude * rad_per_deg
    
        let sinDlat = sin(dlat_rad/2)
        let sinDlon = sin(dlon_rad/2)
        let a = sinDlat * sinDlat + cos(lat1_rad) * cos(lat2_rad) * sinDlon * sinDlon
        let c = 2.0 * atan2(sqrt(a), sqrt(1-a))
    
        return rm * c
    }
    

提交回复
热议问题