Skip to content

bearing: fix final bearing returning values outside [-180, 180] - #3077

Merged
mfedderly merged 2 commits into
Turfjs:masterfrom
JSap0914:fix/bearing-final-bearing-range
Jun 26, 2026
Merged

bearing: fix final bearing returning values outside [-180, 180]#3077
mfedderly merged 2 commits into
Turfjs:masterfrom
JSap0914:fix/bearing-final-bearing-range

Conversation

@JSap0914

Copy link
Copy Markdown
Contributor

Summary

bearing(start, end, { final: true }) can return values in the range (180, 360) instead of the documented [-180, 180].

Root cause

calculateFinalBearing reverses the point pair and adds 180° to get the final bearing:

let bear = bearing(end, start); // in [-180, 180]
bear = (bear + 180) % 360;      // yields [0, 360) — wrong when bear > 0
return bear;

When bearing(end, start) returns a positive value (e.g. 90°), the result is 270° — outside the documented range and inconsistent with every other bearing API in Turf.

Fix

Add a single normalisation step after the modulo:

return bear > 180 ? bear - 360 : bear;

Concrete example

// Traveling due west along the equator
bearing(point([10, 0]), point([0, 0]), { final: true })
// before: 270   ← wrong
// after:  -90   ← correct

Changes

  • packages/turf-bearing/index.ts: one-line normalisation in calculateFinalBearing
  • packages/turf-bearing/test.ts: new test case covering the westward edge case
  • packages/turf-helpers/README.md: auto-regenerated by the pre-commit hook (not related to this fix)

Resolves the documented contract that bearing() returns values between -180 and 180 degrees.

calculateFinalBearing used (bear + 180) % 360 which yields [0, 360)
when bear > 0, violating the documented [-180, 180] return range.

Add one normalisation step: if the result exceeds 180, subtract 360.

Example: bearing(point([10,0]), point([0,0]), { final: true }) now
correctly returns -90 instead of 270.
Copilot AI review requested due to automatic review settings June 22, 2026 03:00

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@mfedderly mfedderly added this to the v7.4 milestone Jun 26, 2026

@mfedderly mfedderly left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@turf/rhumb-bearing seems to already handle this case.

@mfedderly
mfedderly merged commit 85f7717 into Turfjs:master Jun 26, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants