0
votes

I am calculating the nearest distance of two points (latitude, longitude). My code is as below:

R = 6378.0
distsecKM = []

for i in range(len(pLat)):
    lat1 = math.radians(pLat[i])
    lon1 = math.radians(pLon[i])
    temp = []
    for j in range(len(secondaryLat)):
        lat2 = math.radians(secondaryLat[j])
        lon2 = math.radians(secondaryLon[j])
        diffLat = lat2 - lat1
        diffLon = lon2 - lon1
        a = ((math.sin(diffLat / 2))**2) + (math.cos(lat2)) * (math.cos(lat1)) * ((math.sin(diffLon / 2))**2)
        b = 2 * math.atan2(sqrt(a), sqrt(1 - a))
        dist = R * b
        temp.append(dist)
    distsecKM.append(min(temp))

I am getting the smallest distance between point1(lat1,lon1) and point2(lat2,lon2). However, I also want to get the lat2 and lon2 used to calculate the smallest distance and save it to a list perhaps.

How do I go about this?

2

2 Answers

1
votes

(I'm assuming you meant temp and temp2 to be the same.)

Instead of

temp.append(dist)

you can simply

temp.append((dist, lat2, lon2))

The calculation of min(temp) works the same as before, because tuples are sorted in lexicographical order (i.e. by first item, if equal by second item, etc.).

If you don't change anything else, distsecKM will then contain a tuple, instead of a single value, which you must unpack, e.g. like so:

dist, lat, lon = distsecKM[0]

Or if you are using it in a for loop:

for dist, lat, lon in distsecKM:
    # ...
-1
votes

You can create a list

lat2List = []
lon2List = []

and then keep appending values to these lists separately.

lat2List.push(lat2)
lon2List.push(lon2)