从学位获得方向

时间:2018-02-12 15:59:43

标签: javascript math

我构建了一个能够计算设备标题的小型罗盘项目。所以我得到的是一个函数,它返回当前航向的 0°和360°之间的值。

我想得到的是来自如下数组的当前标题方向的匹配值:(["North", "North-East", "East", "South-East", "South", "South-West", "West", "North-West"]

img

(请记住:北= 0°/ 359°)

但是我不知道如何获得这样的结果&以下几行是我到目前为止所得到的,但它似乎不起作用:

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]
}

任何帮助都将非常感谢,提前感谢。

2 个答案:

答案 0 :(得分:1)

此解决方案应考虑所有可能的情况:

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

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

console.log( getDirection(0) );
console.log( getDirection(359) );
console.log( getDirection(45) );
console.log( getDirection(-120) );
console.log( getDirection(180) );

答案 1 :(得分:0)

选项是将值从比例[0,360]转换为比例[0,8]

其中[0,8]是方向数组的长度

var scale = function (value, from, to) {
    percent = (Math.abs(value) - Math.abs(from[0])) / (Math.abs(from[1]) - Math.abs(from[0]));
    return percent * (Math.abs(to[1]) - Math.abs(to[0])) + Math.abs(to[0]);
}

var directions = ["North", "North-East", "East", "South-East", "South", "South-West", "West", "North-West"]
var direction =  Math.round(scale(60,[0,360],[0,8]))
console.log(directions[direction]);