在 Python 中根据 GPS 坐标计算基本方向

Posted

技术标签:

【中文标题】在 Python 中根据 GPS 坐标计算基本方向【英文标题】:Calculate cardinal direction from GPS coordinates in Python 【发布时间】:2018-05-19 10:42:58 【问题描述】:

如何在 Python 中计算第二个地理坐标点的基本方向? 我需要知道两个不同位置的距离和方向。

示例: 工作:坐标 41.4107628,2.1745004 家 : 坐标 41.4126728,2.1704725

from geopy.distance import vincenty
work = geopy.Point(41.4107628,2.1745004)
home = geopy.Point(41.4126728,2.1704725)
print(vincenty(home, work))
0.398011015257 km

我想知道第二个点相对于第一个点位于哪个方向(例如:北、西北等)...

在此先感谢

【问题讨论】:

【参考方案1】:

使用我的 python 包 geographiclib.

之后

pip install geographiclib

$ python
Python 2.7.14 (default, Nov  2 2017, 18:42:05) 
>>> from geographiclib.geodesic import Geodesic
>>> geod = Geodesic.WGS84
>>> g = geod.Inverse(41.4107628,2.1745004, 41.4126728,2.1704725)
>>> print "The initial direction is :.3f degrees.".format(g['azi1'])
The initial direction is -57.792 degrees.

方向是从北顺时针测量的。所以 -57.8 度 = 302.2 度 = 西北偏西;见Points of the compass。

【讨论】:

感谢 cffk,但如何将 -57 度转换为方向?这是否意味着 WSW ?从N逆时针方向?【参考方案2】:

为清楚起见进行编辑:这是一个近似值,可以说明大致方向。使用下面的链接获取简单的在线计算器。否则请按照提供的其他答案。

坐标系中的第一个值代表北/南方向,第二个值代表东/西。简单的减法将提供一个大致的方向。例如从 A 中减去 B,我们得到:

41.4126728 - 41.4107628 = 0.00191

2.1704725 - 2.1745004 = - 0.0040279

这表明要从 A 点到达 B 点,您需要向北(正值)西(负值)方向行驶。 可以通过使用三角法找到精确的角度(将每个值视为直角三角形的一条边)。 正如 cmets 中所述,三角法不足以进行精确计算。

您可能会觉得这个网站很有趣:https://www.movable-type.co.uk/scripts/latlong.html

【讨论】:

你不能在球体上使用二维三角函数!所有的计算都会出错!您链接的网站很好,并且显示了正确的示例。 好点。我想我假设相对方向近似不会有太大区别。或者我只是没有想。谢谢指正。【参考方案3】:

FWIW,我需要北、南、东、西等作为文本。 这是我的(老式程序员)代码:

import math

def calcBearing (lat1, long1, lat2, long2):
    dLon = (long2 - long1)
    x = math.cos(math.radians(lat2)) * math.sin(math.radians(dLon))
    y = math.cos(math.radians(lat1)) * math.sin(math.radians(lat2)) - math.sin(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.cos(math.radians(dLon))
    bearing = math.atan2(x,y)   # use atan2 to determine the quadrant
    bearing = math.degrees(bearing)

    return bearing

def calcNSEW(lat1, long1, lat2, long2):
    points = ["north", "north east", "east", "south east", "south", "south west", "west", "north west"]
    bearing = calcBearing(lat1, long1, lat2, long2)
    bearing += 22.5
    bearing = bearing % 360
    bearing = int(bearing / 45) # values 0 to 7
    NSEW = points [bearing]

    return NSEW

# White house 38.8977° N, 77.0365° W
lat1 = 38.8976763
long1 = -77.0365298
# Lincoln memorial 38.8893° N, 77.0506° W
lat2 = 38.8893
long2 = -77.0506

points = calcNSEW(lat1, long1, lat2, long2)
print ("The Lincoln memorial is " + points + " of the White House")
print ("Actually bearing of 231.88 degrees")

print ("Output says: The Lincoln memorial is south west of the White House ")

【讨论】:

以上是关于在 Python 中根据 GPS 坐标计算基本方向的主要内容,如果未能解决你的问题,请参考以下文章

Python地理位置信息库geopy的使用:根据中心点坐标,方向,距离计算坐标

在给定点、方位角和距离的情况下计算 gps 坐标

JSON方向解析器是在两个GPS坐标之间绘制方向的唯一方法吗?

请问根据GPS坐标点怎么计算面积?

计算在 X 和 Y 和 Z 方向上具有一个坐标 + 距离的新坐标

在GPS经纬度中,啥是绝对84坐标 , 相对84坐标