I have a list of locations with their names and coordinate points.
I'm trying to find the closest location pairs for each location and print the current location name, the distance to the closest location, and the closest location name.
- location names stored in column 0
- latitudes are stored in column 5
- longitudes are stored in column 8
I have tried to work this out but I get this error after a few iterations.
---------------------------------------------------------------------------
24 for j in range(len(data[i])):
25 if(i != j):
---> 26 distance = get_distance(float(data[i][5]),float(data[i][8]),float(data[j][5]),float(data[j][8]))
27 temp = str(data[i][0])
28 if (min > distance):
ValueError: could not convert string to float:
I get results before this error, but I suspect that the results are wrong. Not sure what the issue is, any help would be greatly appreciated.
Edit: My issue now is that the algorithm is broken. The closest location it returns is always the same target location. The distance it returns varies from like 80 miles to thousands of miles which I know is not the case. All locations are within a few hundred miles of each other.
import math
import csv
with open("Locations.csv") as f:
def get_distance(lat_1, lng_1, lat_2, lng_2):
d_lat = lat_2 - lat_1
d_lng = lng_2 - lng_1
temp = (
math.sin(d_lat / 2) ** 2
+ math.cos(lat_1)
* math.cos(lat_2)
* math.sin(d_lng / 2) ** 2
)
return 3963.1676 * (2 * math.atan2(math.sqrt(temp), math.sqrt(1
- temp)))
min = float(9000)
temp = ''
closest = ''
reader = csv.reader(f)
next(reader) # skip header
for i in range(len(data)):
for j in range(len(data[i])):
if(i != j):
distance = get_distance(float(data[i][5]),float(data[i][8]),float(data[j][5]), float(data[j][8]))
temp = str(data[i][0])
if (min > distance):
min = distance
closest = temp
print(str(data[i][0]) +" " + str(min) + " " + closest)
min = 90000
closest = ''