4

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.

VisioN
  • 143,310
  • 32
  • 282
  • 281

1 Answers1

15

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) );
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Nice solution but please edit the directions like this: `["North", "North-West", "West", "South-West", "South", "South-East", "East", "North-East"]`. Exact the solution I was looking for. –  Feb 12 '18 at 16:18
  • @JaneDeverly Yep, thanks. I've just copied the directions from your question `:)` Now fixed. – VisioN Feb 12 '18 at 16:20
  • 1
    Won't this method return inverted values as for example for angle 90, it should return east but the function says west. – Aayush Mall Aug 06 '20 at 20:42