chow path in map based on routes in python

To show a path in a map based on routes, you can make use of several python libraries such as geopy, osmnx, networkx, and folium.

Here's a simple step by step guide on how to achieve this:

  1. First, you need to determine the source and destination points. You can do this by using a geocoding API like geopy, which can convert addresses into latitude/longitude coordinates.
main.py
from geopy.geocoders import Nominatim

# initialize Nominatim geocoder
geolocator = Nominatim(user_agent="my-application")

# define source and destination addresses
start = "1600 Amphitheatre Parkway, Mountain View, CA"
end = "1 Infinite Loop, Cupertino, CA"

# get latitude and longitude coordinates for source and destination
start_location = geolocator.geocode(start)
end_location = geolocator.geocode(end)

start_coords = (start_location.latitude, start_location.longitude)
end_coords = (end_location.latitude, end_location.longitude)
540 chars
16 lines
  1. Next, you can use the osmnx library to download the street network graph for your area of interest. This will allow you to calculate the shortest path between your source and destination points based on the available road network.
main.py
import osmnx as ox

# download street network graph within 1km radius of start location
G = ox.graph_from_point(start_coords, distance=1000, network_type="drive")

# calculate the shortest path between start and end points
route = ox.shortest_path(G, start_coords, end_coords, weight="length")

# convert route to a list of latitude/longitude coordinates
route_coords = ox.get_route_edge_attributes(G, route, attribute="geometry")
route_coords = [list(reversed(line)) for line in route_coords]
494 chars
12 lines
  1. Finally, you can use the folium library to visualize the route on a map. You can create a FeatureGroup for the route and add it to a Map object.
main.py
import folium

# create a new map centered on the start location
m = folium.Map(location=start_coords, zoom_start=12)

# add marker for start and end locations
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)

# add the route to the map as a FeatureGroup
route_fg = folium.FeatureGroup(name="Route")
folium.PolyLine(route_coords, color="blue", weight=5).add_to(route_fg)
route_fg.add_to(m)

# add layer control to the map
folium.LayerControl().add_to(m)

# display the map
m
582 chars
20 lines

This will display a map showing the shortest route between the start and end points, with markers indicating the start and end locations.

gistlibby LogSnag