Skip to content

Instantly share code, notes, and snippets.

@pianosnake
Last active April 18, 2018 16:00
Show Gist options
  • Save pianosnake/2dfca3c926a5e43d01b41efd54cc57ed to your computer and use it in GitHub Desktop.
Save pianosnake/2dfca3c926a5e43d01b41efd54cc57ed to your computer and use it in GitHub Desktop.
Convert bearing (0-360 degrees) to cardinal direction (N, NW, etc...)
//divide 360 into 16 equal slices
const degrees = (new Array(16)).fill(null).map((x, i) => 360/16 * i + 11.25);
const directions = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
function cardinalDirection(bearing) {
for (let i = 0, l = degrees.length; i < l; i++) {
if (bearing < degrees[i]) return directions[i];
if (i == l - 1) return directions[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment