How to Calculate Distances between Locations using Geopy in Python | Python Tutorials

preview_player
Показать описание
In this Python tutorial, we'll learn how to use the calculate_distance() function in the geopy package to calculate distances between two locations.

This function is great for a variety of applications, such as finding the distance between cities or calculating the length of a road trip.

We'll go step-by-step through the code, so even if you're new to Python, you'll be able to follow along. By the end of this video, you'll have a solid understanding of how to calculate distances using geopy in Python.
Рекомендации по теме
Комментарии
Автор

Here is the code. Please install geopy using !pip install geopy before running the code :


from geopy.geocoders import Nominatim
from geopy.distance import distance

def calculate_distance(location1, location2):
geolocator =
location1 = geolocator.geocode(location1)
location2 = geolocator.geocode(location2)
if location1 and location2:
distance_in_km = distance((location1.latitude, location1.longitude),
(location2.latitude, location2.longitude)).km
return distance_in_km
else:
return None

# Example
location1 = 'Delhi'
location2 = 'Bengaluru'
distance_in_km = calculate_distance(location1, location2)
if distance_in_km:
print(f"The distance between {location1} and {location2} is {distance_in_km:.2f} km.")
else:
print("One or both of the locations could not be found.")

funwithpython