user9225081
user9225081

Reputation:

Get direction from degrees

I built a small compass project that is able to calculate the devices heading. SO what I got is a function that returns a value between 0° and 360° for the current heading.

What I like to get is a matching value for the current heading direction from an array like this: (["North", "North-East", "East", "South-East", "South", "South-West", "West", "North-West"])

img

(keep in mind: North = 0° / 359°)


However I got no idea how to get a result like this & this few lines below are all that I got so far but it doesn't seems working:

var directions = ["North", "North-East", "East", "South-East", "South", "South-West", "West", "North-West"]

function getDirection(heading) {
   var index = Math.round((heading/8)/5,625)
   return directions[index]
}

Any help would be very appreciated, thanks in advance.

Upvotes: 4

Views: 5229

Answers (1)

VisioN
VisioN

Reputation: 145378

This solution should take all possible scenarios in consideration:

var index = Math.round(((angle %= 360) < 0 ? angle + 360 : angle) / 45) % 8;

function getDirection(angle) {
    var directions = ['North', 'North-East', 'East', 'South-East', 'South', 'South-West', 'West', 'North-West'];
    var index = Math.round(((angle %= 360) < 0 ? angle + 360 : angle) / 45) % 8;
    return directions[index];
}

console.log( getDirection(0) );
console.log( getDirection(45) );
console.log( getDirection(180) );
console.log( getDirection(99) );
console.log( getDirection(275) );
console.log( getDirection(-120) );
console.log( getDirection(587) );

Upvotes: 15

Related Questions