show direction using map in python

To show directions using a map in Python, we can use the folium and geopy libraries.

Here is a sample code that demonstrates how to show directions using a map in Python:

main.py
import folium
from geopy.geocoders import Nominatim
from geopy import distance

start_location = "New York City"
end_location = "Washington DC"

# Get coordinates of start and end locations
geolocator = Nominatim(user_agent="my_app")
start_address = geolocator.geocode(start_location)
end_address = geolocator.geocode(end_location)

start_coords = (start_address.latitude, start_address.longitude)
end_coords = (end_address.latitude, end_address.longitude)

# Create map centered around start location
m = folium.Map(location=start_coords, zoom_start=6)

# Add start and end markers to the map
folium.Marker(location=start_coords, icon=folium.Icon(color="green")).add_to(m)
folium.Marker(location=end_coords, icon=folium.Icon(color="red")).add_to(m)

# Draw a line between start and end locations
line = folium.PolyLine(locations=[start_coords, end_coords], color="blue", weight=5)
line.add_to(m)

# Calculate and show the distance between the two locations
d = distance.distance(start_coords, end_coords).km
print("Distance between the two locations is {:.2f} kilometers".format(d))

# Display the map
m
1105 chars
33 lines

In this code, we first get the coordinates of the start and end locations using the geopy library. We then create a folium map centered around the start location, and add markers for the start and end locations to the map. We also draw a line connecting the two locations.

Finally, we calculate the distance between the two locations using the geopy library and print it to the console. We display the map using the m variable.

gistlibby LogSnag