身材匀称的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)
将打印
第二个坐标:(1.0, 0.0)
第二个 x 值:1.0
第二个 y 值:0.0
您可以使用它来获取lat
and lon
您的每个 GPS 坐标的值LineString
where x
代表lat
and y
代表lon
。然后使用半正矢公式可以计算地理距离。经过快速搜索后我发现这个答案 https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points它提供了半正弦公式函数的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
第一个有效,但必须打字很烦人haversine(point1[1], point1[0]...)