Skip to content

Instantly share code, notes, and snippets.

@Jxck-S
Created March 8, 2021 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jxck-S/148d8de79d087da6b5155c4ad8c21d79 to your computer and use it in GitHub Desktop.
Save Jxck-S/148d8de79d087da6b5155c4ad8c21d79 to your computer and use it in GitHub Desktop.
Gets the closest airport from a coordinate using OpenFlights airports.dat
def get_closest_airport(latitude, longitude):
import csv
from geopy.distance import geodesic
plane = (latitude, longitude)
header = ["id", "name", "city", "country", "iata", "icao", "lat", "lng", "alt", "tz", "dst", "tz_db", "type", "source"]
with open('airports.dat', encoding='utf-8') as airport_dat:
airport_dat_reader = csv.DictReader(filter(lambda row: row[0]!='#', airport_dat), header)
for airport in airport_dat_reader:
airport_coord = float(airport['lat']), float(airport['lng'])
airport_dist = float((geodesic(plane, airport_coord).mi))
if "closest_airport_dict" not in locals():
closest_airport_dict = airport
closest_airport_dist = airport_dist
elif airport_dist < closest_airport_dist:
closest_airport_dict = airport
closest_airport_dist = airport_dist
closest_airport_dict['distance'] = closest_airport_dist
print("Closest Airport:", closest_airport_dict['icao'], closest_airport_dict['name'], closest_airport_dist, "Miles Away")
return closest_airport_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment