Skip to content

Commit 1dffc4c

Browse files
author
Federico
committed
Added a new project called 'Distance Calculator'
1 parent 805e08f commit 1dffc4c

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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()

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,5 @@ wsproto==1.2.0
5757
beautifulsoup4~=4.12.2
5858
pypdf2~=3.0.1
5959
pygame~=2.4.0
60-
customtkinter~=5.1.3
60+
customtkinter~=5.1.3
61+
geopy~=2.3.0

0 commit comments

Comments
 (0)