晚了晚会,但有希望的贡献。在使用geopy的scw 答案的基础上,我编写了一个小函数,该函数针对具有任意多个坐标的匀称LineString对象进行计算。它使用pairs
来自Stackoverflow 的迭代器。
主要功能:文档字符串比代码片段长得多。
def line_length(line):
"""Calculate length of a line in meters, given in geographic coordinates.
Args:
line: a shapely LineString object with WGS 84 coordinates
Returns:
Length of line in meters
"""
# Swap shapely (lonlat) to geopy (latlon) points
latlon = lambda lonlat: (lonlat[1], lonlat[0])
total_length = sum(distance(latlon(a), latlon(b)).meters
for (a, b) in pairs(line.coords))
return round(total_length, 0)
def pairs(lst):
"""Iterate over a list in overlapping pairs without wrap-around.
Args:
lst: an iterable/list
Returns:
Yields a pair of consecutive elements (lst[k], lst[k+1]) of lst. Last
call yields the last two elements.
Example:
lst = [4, 7, 11, 2]
pairs(lst) yields (4, 7), (7, 11), (11, 2)
Source:
/programming/1257413/1257446#1257446
"""
i = iter(lst)
prev = i.next()
for item in i:
yield prev, item
prev = item