I have this program in which I want it to return a few places from a list, in order of which is closest to a set point with longitude and latitude. I want it to return, for example, the five closest places that are in my list of tuples of longs and lats, in order, to the set point. I am doing this with Python.
Asked
Active
Viewed 944 times
0
-
1https://en.wikipedia.org/wiki/Haversine_formula, https://stackoverflow.com/a/4913653 – bc291 Feb 26 '19 at 14:16
-
Compare each place to central point by formula above. Then simply sort by distance and here you go. – bc291 Feb 26 '19 at 14:19
-
Thanks for the quick response! I'll check it out! – CompuGenuis Programs Feb 26 '19 at 14:24
1 Answers
3
Using: Haversine, you can just do:
from math import radians, cos, sin, asin, sqrt
center = (lon, lat)
points = [(lon1, lat1), (lon2, lat2), (lon3, lat3), (lon4, lat4), (lon5, lat5))
altogether = [list(center) + list(item) for item in points]
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
distances = list(map(lambda a: haversine(*a), altogether))
-
What would I put in center? The current position? And what is tt? – CompuGenuis Programs Feb 26 '19 at 18:23
-
-