Created
October 11, 2023 06:05
-
-
Save renesansz/e0117b53813a3b54bc6640a79ff430cb to your computer and use it in GitHub Desktop.
Nearest landmark computation based on lat/long coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def haversine(lat1, long1, lat2, long2): | |
# Radius of the Earth in kilometers | |
R = 6371 | |
# Convert latitude and longitude from degrees to radians | |
lat1, long1, lat2, long2 = map(math.radians, [lat1, long1, lat2, long2]) | |
# Differences in latitude and longitude | |
dlat = lat2 - lat1 | |
dlong = long2 - long1 | |
# Haversine formula | |
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlong/2)**2 | |
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) | |
distance = R * c | |
return distance | |
def find_nearest_landmark(user_lat, user_long, landmarks): | |
nearest_landmark = None | |
min_distance = float('inf') | |
for landmark in landmarks: | |
landmark_lat = landmark['latitude'] | |
landmark_long = landmark['longitude'] | |
distance = haversine(user_lat, user_long, landmark_lat, landmark_long) | |
if distance < min_distance: | |
min_distance = distance | |
nearest_landmark = landmark | |
return nearest_landmark, min_distance | |
# Example usage: | |
user_lat = 40.7128 | |
user_long = -74.0060 | |
landmarks = [ | |
{"name": "Statue of Liberty", "latitude": 40.6892, "longitude": -74.0445}, | |
{"name": "Empire State Building", "latitude": 40.748817, "longitude": -73.985428}, | |
# Add more landmarks to the list | |
] | |
nearest, distance = find_nearest_landmark(user_lat, user_long, landmarks) | |
print(f"The nearest landmark is {nearest['name']} at a distance of {distance} km.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment