javascript - 假设我在笛卡尔平面 (JavaScript) 上有原点 (0, 0) 和点 (10, -10),我将如何计算“北”的方位?
问题描述
笛卡尔坐标中的点 (x1, y1)
之间的“轴承”:
- 原点 (0, 0) 和点 (10, 0) 为 90 度
- 原点 (0, 0) 和点 (10, -10) 为 135 度
- 原点 (0, 0) 和点 (0, -10) 是 180 度等。
非常感谢您的帮助,谢谢!
// 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
解决方案
正如 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
推荐阅读
- ruby-on-rails - How to upload google doc file or drive file in drive folder with google drive ruby gem?
- reactjs - How to access react app which is ran in docker container?
- mqtt - 如何处理“OSError:可用接口已关闭”错误消息?
- angular - 在哪里声明 HTMLElementTagNameMap 以获取 Angular 元素的类型?
- google-contacts-api - 受限范围 OAuth 验证
- javascript - 如何在 Electron 中获取窗口 z-index、z-order 或窗口顺序?
- android - 具有动态图标大小的侧边栏菜单
- java - 如何在 Android Studio 中自动替换为 lambda 表达式
- database - Postgres 检查是否插入了任何新行
- php - 检查用户是否将正确的输入发送到 date_create_from_format 函数