Calculating bearing and distance between two lat and long

Dears,

How can I calculate the bearing between two lat and long?

I'm not using the GPS, neither sensors, nor any other system... I'll use an internal database of points and its lat and long.


The distance is working properly, but the bearing is not!

Can you help me?


//: Playground - noun: a place where people can play

import CoreLocation
import Foundation
import UIKit

let coordinate₀ = CLLocation(latitude: 0.0, longitude: 0.0)
let coordinate₁ = CLLocation(latitude: -24.0, longitude: -47.0)

let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters


public func bearing(to destination: CLLocation) -> Double {

    let lat1 = .pi * coordinate₀.coordinate.latitude / 180.0
    let long1 = .pi * coordinate₀.coordinate.longitude / 180.0
    let lat2 = .pi * coordinate₁.coordinate.latitude / 180.0
    let long2 = .pi * coordinate₁.coordinate.longitude / 180.0
    

    let rads = atan2(
        sin(long2 - long1) * cos(lat2),
        cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(long2 - long1))
    let degrees = rads * 180 / Double.pi
    
    return (degrees+360).truncatingRemainder(dividingBy: 360)
}

let bearing = bearing(to: coordinate₁)

Accepted Reply

Hello Claude..


I was looking for the code, but I got it...

I'm learning, day by day, and with your help things are getting better..


Thank you

Replies

Is it the calculation formula you are looking for ?


A Google search will give you the answer, such as here:

θ = atan2( sin Δλ ⋅ cos φ2 , cos φ1 ⋅ sin φ2 − sin φ1 ⋅ cos φ2 ⋅ cos Δλ )

h ttps://www.movable-type.co.uk/scripts/latlong.html

Hello Claude..


I was looking for the code, but I got it...

I'm learning, day by day, and with your help things are getting better..


Thank you

can you please share your code? i am also looking for this.