我将运行数据表示为 Shapely LineStrings,其中 LineString 中的每个点都是一个坐标。我试图计算出以英里为单位的 LineString 长度。我知道 LineString 有一个 length
方法,但我不知道结果的单位是什么。
例如,我知道运行的距离是 0.13 英里,但是当我打印出 runs[0].length
时,我得到 0.00198245721108。我认为这是因为 LineString 位于笛卡尔坐标系中,但我不完全确定。
最佳答案
Shapely 的 LineString
类提供了一个 coords
方法,该方法返回构成 LineString
的所有坐标。例如:
from shapely.geometry import LineString
# Create a LineString to mess around with
coordinates = [(0, 0), (1, 0)]
line1 = LineString(coordinates)
# Grab the second coordinate along with its x and y values using standard array indexing
secondCoord = line1.coords[1]
x2 = secondCoord[0]
y2 = secondCoord[1]
# Print values to console to verify code worked
print "Second Coordinate: " + str(secondCord)
print "Second x Value: " + str(x2)
print "Second y Value: " + str(y2)
将打印
Second Coordinate: (1.0, 0.0)
Second x Value: 1.0
Second y Value: 0.0
您可以使用它来获取 LineString
中每个 GPS 坐标的 lat
和 lon
值,其中 x
> 代表lat
,y
代表lon
。然后使用半正矢公式可以计算地理距离。快速搜索后我发现 this answer它提供了半正弦公式函数的 Python 代码,我已经验证了它的工作原理。然而,这只是给你两个点之间的距离,所以如果你的 GPS 数据中有转弯,你将必须计算每个单独点之间的距离,而不是起点和终点的距离。这是我使用的代码:
from shapely.geometry import LineString
from math import radians, cos, sin, asin, sqrt
# Calculates distance between 2 GPS coordinates
def haversine(lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 3956 # Radius of earth in kilometers. Use 3956 for miles
return c * r
for line in listOfLines:
numCoords = len(line.coords) - 1
distance = 0
for i in range(0, numCoords):
point1 = line.coords[i]
point2 = line.coords[i + 1]
distance += haversine(point1[0], point1[1], point2[0], point2[1])
print distance
如果您只对一个 LineString
执行此操作,则可以摆脱外部 for
循环,但我需要计算几次运行的距离。另请注意,如果您从链接中的答案获取代码,我已经切换了函数参数,因为提供的答案首先有 lon
,它可以工作,但必须输入 havesine(点1[1],点1[0]...)
关于python - 线串长度(以英里为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30020930/