Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valid way to calculate angle between 2 CLLocations?

Is this a valid way to calculate an angle (in radians) from one CLLocation to another?

-(float)angleFromLocation:(CLLocationCoordinate2D)start toLocation:(CLLocationCoordinate2D)end {
float deltaX = start.latitude - end.latitude;
float deltaY = start.longitude - end.longitude;
float ang = atan2(deltaY, deltaX);

return ang;}

Please advise!

Any help will be much appreciated.

like image 586
David Avatar asked Sep 02 '25 17:09

David


1 Answers

Swift 5 version:

extension FloatingPoint {

    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

extension CLLocationCoordinate2D {
       
    func heading(to: CLLocationCoordinate2D) -> Double {
        let lat1 = self.latitude.degreesToRadians
        let lon1 = self.longitude.degreesToRadians

        let lat2 = to.latitude.degreesToRadians
        let lon2 = to.longitude.degreesToRadians

        let dLon = lon2 - lon1
        let y = sin(dLon) * cos(lat2)
        let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)

        let headingDegrees = atan2(y, x).radiansToDegrees
        if headingDegrees >= 0 {
            return headingDegrees
        } else {
            return headingDegrees + 360
        }
    }
}
like image 147
coldfire Avatar answered Sep 06 '25 20:09

coldfire