-1

I have been trying to build a piece of code that computes the heading change between two points. My approach is to take the 'getBearing()' value that android returns for each of them, and subtract the first with the last.

But a problem arises in extreme cases: android returns a value ranged ]0;360], which means that some subtractions will return huge heading changes, even though the change may have been smaller.

For example, if walking slightly angle towards north, with a bearing of 355º and then changing to 5º degrees, the heading change value should read 10º, but with my method it will read -350º.

Any idea on how to find a way to compute heading changes using these values, but returning the appropriate change accoordingly?

NOTE: The heading change must also denote the direction of the change.

ravemir
  • 1,153
  • 2
  • 13
  • 29

2 Answers2

1

All angles (in degrees) are only defined modulo 360. So -350º is the same angle as 10º. If you want the angle with the lowest absolute value, then simply add some code as follows:

float angle = 355;   // the input angle, whatever it turns out to be
while (angle <= -180) angle += 360;
while (angle > 180) angle -= 360;
Stochastically
  • 7,616
  • 5
  • 30
  • 58
  • This is clever, but it doesn't give me a result with direction. – ravemir May 25 '13 at 19:06
  • The bearing does give you the direction :-). It doesn't matter whether you add or subtract 360 degrees, the angle that's specified is the same, and hence it's the same direction. For example, -90º is the same direction as +270º, but however you look at it, +90º is the exact opposite direction. – Stochastically May 25 '13 at 22:39
0

If you are not concerned with the direction and only the difference then you can compute as follow

(bearingA - bearingB + 360) % 360;
Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54
  • I am concerned with the direction. But out of curiosity, is B the destination bearing? Or origin? – ravemir May 25 '13 at 19:05
  • It makes no difference whether B is destination or origin. You get the same answer with (bearingB - bearingA + 360) % 360. You can infer the direction from each bearing. – Hoan Nguyen May 25 '13 at 19:08
  • -350 should not be a problem because you can then interpret as turning east by 10 degree. Otherwise how can you distinguish between 5 and 345. – Hoan Nguyen May 25 '13 at 19:21