|
| 1 | +from dataclasses import dataclass |
| 2 | +from geopy.geocoders import Nominatim |
| 3 | +from geopy.distance import geodesic |
| 4 | + |
| 5 | + |
| 6 | +@dataclass |
| 7 | +class Coordinates: |
| 8 | + latitude: float |
| 9 | + longitude: float |
| 10 | + |
| 11 | + def coordinates(self): |
| 12 | + return self.latitude, self.longitude |
| 13 | + |
| 14 | + |
| 15 | +def get_coordinates(address: str) -> Coordinates | None: |
| 16 | + """Creates a geolocator that returns coordinates for the given address.""" |
| 17 | + |
| 18 | + geolocator = Nominatim(user_agent="distance_calculator") |
| 19 | + location = geolocator.geocode(address) |
| 20 | + |
| 21 | + if location: |
| 22 | + return Coordinates(latitude=location.latitude, longitude=location.longitude) |
| 23 | + |
| 24 | + |
| 25 | +def calculate_distance_km(home: Coordinates, target: Coordinates) -> float | None: |
| 26 | + """Calculates the distance in km for the home coordinates and the target coordinates.""" |
| 27 | + |
| 28 | + if home and target: |
| 29 | + distance: float = geodesic(home.coordinates(), target.coordinates()).kilometers |
| 30 | + return distance |
| 31 | + |
| 32 | + |
| 33 | +def get_distance_km(home: str, target: str) -> float | None: |
| 34 | + """Gets the distance and returns it as a float.""" |
| 35 | + |
| 36 | + # Get coordinates |
| 37 | + home_coordinates: Coordinates = get_coordinates(home) |
| 38 | + user_coordinates: Coordinates = get_coordinates(target) |
| 39 | + |
| 40 | + # Calculate the distance |
| 41 | + if distance := calculate_distance_km(home_coordinates, user_coordinates): |
| 42 | + print(f"{home} -> {target}") |
| 43 | + print(f"{distance:.2f} kilometers (apx)") |
| 44 | + return distance |
| 45 | + else: |
| 46 | + print("Failed to calculate the distance.") |
| 47 | + |
| 48 | + |
| 49 | +def main(): |
| 50 | + # Start address for testing |
| 51 | + start_address: str = 'Helsinkigade 10, Copenhagen 2150, Denmark' |
| 52 | + print(f'Start address: {start_address}') |
| 53 | + |
| 54 | + # Get the users address and calculate the distance |
| 55 | + target_address: str = input('Enter an address: ') |
| 56 | + print('Calculating...') |
| 57 | + get_distance_km(start_address, target=target_address) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + main() |
0 commit comments