0

I have a list of lon and lat as csv file and i want to calculate the all distances, the file have arguments like this (-18.4392969, -40.2688762) (-8.3905896, -37.4957717) (-19.952862, -33.173232)

edit: i want to make a code that give me something like this: distance between point A to B and C and B to A and C, C to A and B, and save it to a list distances.

FoE
  • 1
  • 2

1 Answers1

0

Here is a python function to compute the great-circle distance between two locations on Earth given their (latitude, longitude) tuples:

import math

def distance(p1, p2):
    R = 6371 # mean radius of Earth in km

    cphi_1 = math.cos(math.radians(p1[0]))
    cphi_2 = math.cos(math.radians(p2[0]))

    d_phi = math.radians(p2[0] - p1[0])
    d_lam = math.radians(p2[1] - p1[1])

    a =  math.sin(d_phi / 2) ** 2
    a += math.sin(d_lam / 2) ** 2 * cphi_1 * cphi_2
    return 2 * R * math.atan2(abs(a) ** 0.5, abs(1 - a) ** 0.5)


if __name__ == "__main__":
    print(distance((40.2342, -17.9834), (13.3298, -53.1698)))

I tested it against this online calculator, however your may wish to do your own testing before using the code above in your own code.

EDIT to compute all unique pair-wise distances without duplicates, use something like

from itertools import combinations
distances = list(map(distance, *zip(*combinations(lat_lon_list, 2))))
Dillon Davis
  • 6,679
  • 2
  • 15
  • 37
  • actually i could calculate this using haversine package, but i want to make a code that give me something like this: distance between point A to B and C,,, and B to A and C,,, C to A and B, and save it to a list distances. – FoE Jul 24 '18 at 02:20
  • Ah, I misunderstood. I thought you were looking for a haversine package to compute the distance for you. – Dillon Davis Jul 24 '18 at 02:23
  • @FoE updated my answer to include code for all pair-wise combinations – Dillon Davis Jul 24 '18 at 02:31