show distances in map in python

To show distances in a map using Python, you can use the geopy library to find geolocation coordinates of locations and then use folium to plot these coordinates on a map. You may also need to use APIs provided by map services such as Google Maps, Bing Maps, or OpenStreetMap to get the geolocation coordinates.

Here's an example code block using geopy and folium to plot the distance between two locations:

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

# Define locations
location1 = "New York City, NY"
location2 = "Washington, DC"

# Get geolocation coordinates
geolocator = Nominatim(user_agent="my-application")
loc1 = geolocator.geocode(location1)
loc2 = geolocator.geocode(location2)

# Calculate distance
dist = distance.distance((loc1.latitude, loc1.longitude), (loc2.latitude, loc2.longitude)).km

# Create map
my_map = folium.Map(location=[(loc1.latitude+loc2.latitude)/2, (loc1.longitude+loc2.longitude)/2], zoom_start=6)

# Create markers
folium.Marker([loc1.latitude, loc1.longitude], popup=location1).add_to(my_map)
folium.Marker([loc2.latitude, loc2.longitude], popup=location2).add_to(my_map)

# Add distance line
folium.PolyLine(locations=[(loc1.latitude, loc1.longitude), (loc2.latitude, loc2.longitude)], tooltip='Distance: {} km'.format(dist)).add_to(my_map)

# Show map
my_map
925 chars
29 lines

This code will display a map with markers at the two locations and a line that displays the distance between the two locations as a tooltip when hovered over.

gistlibby LogSnag