Reputation: 213
I'm creating a navigation app. I want to know that how many degrees between my current heading and ,say, east. The way I'm doing it is that I'm subtracting the true heading with angle 0, in case of north, 90 degrees in case of east, and so on. When the difference reached to let i: ClosedRange<Double> = 0...20
, I would guess that the heading is facing the intended direction, in this example, east.
I would like to know if this is the perfect methodology or not. I'm still confused if I should use bearings, instead.
//calculate the difference between two angles ( current heading and east angle, 90 degrees)
func cal(firstAngle: Double) -> Double {
var diff = heading - 90
if diff < -360 {
diff += 360
} else if diff > 360 {
diff -= 360
}
return diff
}
// check if the difference falls in the range
let i: ClosedRange<Double> = 0...20
if !(i.contains(k)) {
k = cal(firstAngle: b)
} else if (i.contains(k)) {
let message = "You are heading east"
print(message)
} else {return}
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
var heading = newHeading.trueHeading }
Upvotes: 0
Views: 81
Reputation: 154593
This should work for your needs. Comments in the code:
func cal(heading: Double, desired: Double) -> Double {
// compute adjustment
var angle = desired - heading
// put angle into -360 ... 360 range
angle = angle.truncatingRemainder(dividingBy: 360)
// put angle into -180 ... 180 range
if angle < -180 {
angle += 360
} else if angle > 180 {
angle -= 360
}
return angle
}
// some example calls
cal(heading: 90, desired: 180) // 90
cal(heading: 180, desired: 90) // -90
cal(heading: 350, desired: 90) // 100
cal(heading: 30, desired: 270) // -120
let within20degrees: ClosedRange<Double> = -20...20
let adjust = cal(heading: 105, desired: 90)
if within20degrees ~= adjust {
print("heading in the right direction")
}
heading in the right direction
Upvotes: 1