Author: Geoff Boeing
Use OSMnx to download a street network, calculate a route between two points, and create a Leaflet web map with folium.
import networkx as nx
import osmnx as ox
from IPython.display import IFrame
%matplotlib inline
ox.__version__
# download the street network for Piedmont, CA
G = ox.graph_from_place("Piedmont, California, USA", network_type="drive")
# plot the street network with folium
m1 = ox.plot_graph_folium(G, popup_attribute="name", weight=2, color="#8b0000")
# save as html file then display map as an iframe
filepath = "data/graph.html"
m1.save(filepath)
IFrame(filepath, width=600, height=500)
You can zoom into the street network above or click any edge to get more info.
# use networkx to calculate the shortest path between two nodes
origin_node = list(G.nodes())[0]
destination_node = list(G.nodes())[-1]
route = nx.shortest_path(G, origin_node, destination_node)
# plot the route with folium
# like above, you can pass keyword args along to folium PolyLine to style the lines
m2 = ox.plot_route_folium(G, route, weight=10)
# save as html file then display map as an iframe
filepath = "data/route.html"
m2.save(filepath)
IFrame(filepath, width=600, height=500)
# plot the route with folium on top of the previously created graph_map
m3 = ox.plot_route_folium(G, route, route_map=m1, popup_attribute="length", weight=7)
# save as html file then display map as an iframe
filepath = "data/route_graph.html"
m3.save(filepath)
IFrame(filepath, width=600, height=500)