将纬度和经度转换为位置的问题

时间:2021-04-28 13:14:49

标签: latitude-longitude

我希望能够将球体上的 3d 位置转换为纬度和经度并返回。我尝试使用以下方法转换为纬度和经度:

lat = acos(y / sphere_radius) * 180 / PI
long = atan2(x, z) * 180 / PI

它似乎有效。我得到的一些值是:

(0, 1, 0) -> (0, 0)
(1, 0, 0) -> (90, 90)
(0, 0, 1) -> (90, 0)
(0, 1, 1) -> (45, 0)

所以这意味着 y 是我的向上方向,z 是我的前进方向,我的纬度从 0 到 180,我的经度从 0 到 360。但现在我想将纬度和经度转换回位置向量,所以我在网上找到了这个片段(在 https://stackoverflow.com/a/59720312/13215204):

z = sphere_radius * cos(longitude) * cos(latitude)
x = -sphere_radius * cos(longitude) * sin(latitude)
y = sphere_radius * sin(latitude)

它确实返回了球体上的一个点,当我更改纬度和经度时,该点甚至会在周围移动,但位置不正确。例如,如果我首先将点 (1, 0, 0) 转换为 (90, 90),然后尝试将其转换回来,它会返回 (-0.4005763, 0.8939967, 0.20077)。我听说您需要先转换回弧度,但这似乎没有帮助(而是返回 (4.371139e-08, 1, 1.910685e-15))。也许我只需要在周围翻转一些正弦和余弦?

1 个答案:

答案 0 :(得分:0)

现在可以使用了! 这些是我最终使用的方法(在 C# 中,Mathf 是 Unity 的一部分,但我相信您可以找到其他能够轻松完成 sin、cos、acos 和 atan 的库)

public static Vector2 ToLatLon(this Vector3 vector, float sphere_radius)
{
    return new Vector2(
        Mathf.Acos(vector.y / sphere_radius),
        Mathf.Atan2(vector.x, vector.z)
    );
}

public static Vector3 ToVector(this Vector2 latlon, float sphere_radius)
{
    return new Vector3(
         sphere_radius * Mathf.Sin(latlon.y) * Mathf.Sin(latlon.x),
         sphere_radius * Mathf.Cos(latlon.x),
         sphere_radius * Mathf.Cos(latlon.y) * Mathf.Sin(latlon.x)
    );
}

我的 x、y 和 z 方程的顺序错误,并且在计算 x 时还必须从 sphere_radius 中删除减号。我还删除了纬度和经度从弧度到度的转换,因为不需要它们(除了更容易阅读)。因此,当我需要以度为单位的值进行调试时,我改为使用 Mathf.Rad2Deg 在函数外部进行度数的转换。

相关问题