简体   繁体   中英

Distance between list of points based on latitude/longitude

so I have this list of coordinates and I need final SUM of distance between them.

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]]

So far I have basic formula for calculating distance between 2 sets of coordinates

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

I am stuck on the next step, I tried creating a different function that uses existing function for distance and just take each set of coordinates and calculate distance and just add the result numbers together.
Thanks for any help.

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

Explanation

  1. combinations(...) from https://docs.python.org/2/library/itertools.html#itertools.combinations provides all combinations of pairs
  2. lambda p: distance(*p[0][:2], *p[1][:2]) computes distance for a pair, with p[0] and p[1] being the first and second elements of a pair
  3. [:2] is a slice to get the first two elements (ie lat/long)
  4. *p[x][:2] provides the unpacking of the first two elements for arguments of the distance function
  5. map(...) generate distance for all pairs
  6. sum(...) sums up the distance of pairs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM