Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating bearing between two CLLocation points in Swift [duplicate]

I'm trying to calculate a bearing between two CLLocation points in swift-only code. I've run into some difficulty and was assuming this is a pretty simple function. Stack overflow didn't seem to have anything listed.

func d2r(degrees : Double) -> Double {     return degrees * M_PI / 180.0 }  func RadiansToDegrees(radians : Double) -> Double {     return radians * 180.0 / M_PI }   func getBearing(fromLoc : CLLocation, toLoc : CLLocation) {      let fLat = d2r(fromLoc.coordinate.latitude)     let fLng = d2r(fromLoc.coordinate.longitude)     let tLat = d2r(toLoc.coordinate.latitude)     let tLng = d2r(toLoc.coordinate.longitude)      var a = CGFloat(sin(fLng-tLng)*cos(tLat));     var b = CGFloat(cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(fLng-tLng))      return atan2(a,b) } 

I'm getting an error with my atan2 call about lvalue cgfloat or something...

like image 443
Jeef Avatar asked Nov 18 '14 15:11

Jeef


People also ask

What is the bearing between two points?

Bearing is a direction measured from north and it tracks angle in clockwise direction with north line which means north represents zero degree, east is 90 degrees, south is 180 degrees and west is 270 degrees.


1 Answers

Here is an Objective-C solution

  • CLLocation Category for Calculating Bearing w/ Haversine function

which can easily be translated to Swift:

func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180.0 } func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / .pi }  func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {      let lat1 = degreesToRadians(degrees: point1.coordinate.latitude)     let lon1 = degreesToRadians(degrees: point1.coordinate.longitude)      let lat2 = degreesToRadians(degrees: point2.coordinate.latitude)     let lon2 = degreesToRadians(degrees: point2.coordinate.longitude)      let dLon = lon2 - lon1      let y = sin(dLon) * cos(lat2)     let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)     let radiansBearing = atan2(y, x)      return radiansToDegrees(radians: radiansBearing) } 

The result type is Double because that is how all location coordinates are stored (CLLocationDegrees is a type alias for Double).

like image 148
Martin R Avatar answered Sep 28 '22 11:09

Martin R