首页 > 解决方案 > 假设我在笛卡尔平面 (JavaScript) 上有原点 (0, 0) 和点 (10, -10),我将如何计算“北”的方位?

问题描述

笛卡尔坐标中的点 (x1, y1)

之间的“轴承”:

非常感谢您的帮助,谢谢!

// Converts from degrees to radians.
function toRadians(degrees) {
  return degrees * Math.PI / 180;
};

// Converts from radians to degrees.
function toDegrees(radians) {
  return radians * 180 / Math.PI;
}

function bearing(destLat, destLng) {
  // startLat, startLng
  startLat = toRadians(0);
  startLng = toRadians(0);
  destLat = toRadians(destLat);
  destLng = toRadians(destLng);

  y = Math.sin(destLng - startLng) * Math.cos(destLat);
  x = Math.cos(startLat) * Math.sin(destLat) -
    Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
  brng = Math.atan2(y, x);
  brng = toDegrees(brng);
  return ((brng + 360) % 360).toFixed(2);
}

console.log(bearing(1023, 1023)); // returns me 208.57 but is supposed to be 135 degrees

在此处输入图像描述

标签: javascriptcoordinates

解决方案


正如 StackOverthrow 之前指出的那样,您从线性距离到弧度的转换是无效的。更重要的是,您的大多数方程式都不正确:这些是将球坐标转换为笛卡尔坐标的方程式 - 然后您将其转换为极坐标。

您已经有了笛卡尔坐标:它们是您的输入(x, y)值。

我在这台机器上没有 JS,但是对于您保留当前代码的部分,这是一个简单的 Python 解决方案:

import math

def bearing(y, x):
    dir = math.degrees(math.atan2(x, y))
    if dir < 0:
        dir += 360
    return dir

root3 = 3**(0.5)
test = [
    ( 1,  root3),
    (-1,  root3),
    (-1, -root3),
    ( 1, -root3),
    ]

for point in test:
    print(point[0],
          round(point[1], 2),
          round(bearing(*point),2)); # returns me 208.57 but is supposed to be 135 degrees

输出(通过手工编辑对齐的列)

 1  1.73  60.0
-1  1.73 120.0
-1 -1.73 240.0
 1 -1.73 300.0

推荐阅读