基于纬度/经度的点列表之间的距离

2024-09-27 21:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这个坐标列表,我需要它们之间距离的最终和

track = [[49.16967, 20.21491, 1343],
        [49.17066, 20.22002, 1373],
        [49.16979, 20.22416, 1408],
        [49.17077, 20.22186, 1422],
        [49.17258, 20.22094, 1467],
        [49.17294, 20.21944, 1460]]

到目前为止,我已经有了计算两组坐标之间距离的基本公式

import math
def distance(lat_start, lon_start, lat_ciel, lon_ciel):
    R = 6371000
    lat_start = math.radians(lat_start)
    lon_start = math.radians(lon_start)
    lat_ciel = math.radians(lat_ciel)
    lon_ciel = math.radians(lon_ciel)
    DiffLat = lat_ciel - lat_start
    DiffLon = lon_ciel - lon_start
    a = math.sin(DiffLat/2) ** 2 + math.cos(lat_start) * math.cos(lat_ciel) * math.sin(DiffLon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    return R * c

我陷入了下一步,我尝试创建一个不同的函数,该函数使用现有的距离函数,只需获取每一组坐标并计算距离,然后将结果数字相加。
谢谢你的帮助


Tags: 函数距离列表mathtracksqrtsincos
1条回答
网友
1楼 · 发布于 2024-09-27 21:29:49
import math
from itertools import combinations

def distance(lat_start, lon_start, lat_ciel, lon_ciel):
    R = 6371000
    lat_start = math.radians(lat_start)
    lon_start = math.radians(lon_start)
    lat_ciel = math.radians(lat_ciel)
    lon_ciel = math.radians(lon_ciel)
    DiffLat = lat_ciel - lat_start
    DiffLon = lon_ciel - lon_start
    a = math.sin(DiffLat/2) ** 2 + math.cos(lat_start) * math.cos(lat_ciel) * math.sin(DiffLon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    return R * c

def sum_distance(track):
  return sum((map(lambda p: distance(*p[0][:2], *p[1][:2]), combinations(track, 2))))

my_track = [[49.16967, 20.21491, 1343],
        [49.17066, 20.22002, 1373],
        [49.16979, 20.22416, 1408],
        [49.17077, 20.22186, 1422],
        [49.17258, 20.22094, 1467],
        [49.17294, 20.21944, 1460]]

print(sum_distance(my_track))   # 5252.0327870706005

解释

  1. 来自的组合(…) https://docs.python.org/2/library/itertools.html#itertools.combinations 提供对的所有组合
  2. lambda p:distance(*p[0][:2],*p[1][:2])计算 配对,其中p[0]和p[1]是配对的第一个和第二个元素
  3. [:2]是获取前两个元素(即lat/long)的切片
  4. *p[x][:2]为距离函数的参数提供前两个元素的解包
  5. 映射(…)为所有对生成距离
  6. sum(…)对成对的距离求和

相关问题 更多 >

    热门问题