Skip to content

Instantly share code, notes, and snippets.

@theKAKAN
Created February 14, 2021 17:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theKAKAN/b40bf54144a6eb90313ad00681e3fbcc to your computer and use it in GitHub Desktop.
Save theKAKAN/b40bf54144a6eb90313ad00681e3fbcc to your computer and use it in GitHub Desktop.
Convert degrees or angles to cardinal direction
function getDirection( angle ){
// We divide it into 16 sections
let directions = ["N","NNE","NE","ENE","E",
"ESE", "SE", "SSE","S",
"SSW","SW","WSW","W",
"WNW","NW","NNW" ];
// This means, every 360 / 16 degree, there's a section change
// So, in our case, every 22.5 degree, there's a section change
// In order to get the correct section, we just need to divide
let section = parseInt( angle/22.5 + 0.5 );
// If our result comes to be x.6, which should normally be rounded off to
// int(x) + 1, but parseInt doesn't care about it
// Hence, we are adding 0.5 to it
// Now we know the section, just need to make sure it's under 16
section = section % 16;
// Now we can return it
return directions[ section ];
}
@theKAKAN
Copy link
Author

Explanation

Let's assume we have divided the compass into 16 sections
So, this means, each section has a range of ( 360 / 16 ) = 22.5 degrees

That means, every 22.5 degree there's a section change.
0 - 22.5 = N
22.5 - 45 = NNE
...and so on

So, we divide our given angle by 22.5 and add 0.5 to it so that it rounds off properly
NOTE: you can skip adding 0.5 if you're using a proper round off function

Then, we return from our array index the result out of 16 ( keeping in mind that it doesn't exceed 16 )

@OctaneInteractive
Copy link

Excellent work, and it saved me a bit of time.

I'm using TypeScript, and here's what I did with the code:

export const getDirection = ( angle: number ): string => {
	let directions: string[] = [
		"N", "NNE", "NE", "ENE",
		"E", "ESE", "SE", "SSE",
		"S", "SSW", "SW", "WSW",
		"W", "WNW", "NW", "NNW"
	]

	const section: number = Math.floor(angle / 22.5 + 0.5)

	return directions[ section % 16 ]
}

Everything appears to be working, so I'm assuming the Math.floor() didn't break anything? As an aside, TypeScript didn't like the parseInt().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment