calculate distances in map in python

To calculate distances on a map in Python, you can use the geopy library. First, you need to install it by running the following command:

main.py
pip install geopy
18 chars
2 lines

Then, you can use the distance function of geopy to calculate the distance between two coordinates in kilometers or miles. Here's an example code snippet:

main.py
from geopy.distance import distance

# Define the coordinates of two points
point_a = (51.5074, -0.1278)  # London
point_b = (40.7128, -74.0060)  # New York

# Calculate the distance between the two points in kilometers
dist_km = distance(point_a, point_b).km

# Calculate the distance between the two points in miles
dist_miles = distance(point_a, point_b).miles

# Print the distances
print(f"The distance between London and New York is {dist_km:.2f} km ({dist_miles:.2f} miles)")
483 chars
15 lines

In this example, we define two points using their coordinates in (latitude, longitude) format. Then, we use the distance function to calculate the distance between the two points. Finally, we print the distance in kilometers and miles using formatted strings.

gistlibby LogSnag