How to calculate the distance between 2 points in a sphere (The Earth) in Swift?

Hi there,

Given 2 points I need to calculate the distance between them on a sphere.
How can I do something like this?

Thanks!

Import Foundation to access trigonometric functions in Swift, and use the standard mathematical formulas to calculate great-circle distance.

1 Like

Hi Nevin.
I must see for here, right?

I found this

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
}

You can also use CoreLocation to do it:

import CoreLocation

let first = CLLocation(latitude: 1.1, longitude: 2.2)
let second = CLLocation(latitude: 1.1, longitude: 2.5)

let distanceInMeters = first.distance(from: second)
3 Likes

Oh, great!
Thank you very much

Warning: because of its rotation pushing mass outwards at the equator, the Earth isn't a sphere, but rather an oblate spheroid.

Approximating point-to-point distance as great-circle distance over a sphere is just that, an approximation, which gets worse over large vertical distances.

4 Likes

Interestingly, Earth’s oblate-spheroid shape caused colonial-era American clocks to be inaccurate.

5 Likes

You want to use Vincenty's formula if you want real accuracy, the haversine formula otherwise. A quick google search on Vincenty's formula in Swift turns up: GitHub - dastrobu/vincenty: Compute vincenty distance in Swift

3 Likes

Great! Thanks