#!/usr/bin/env python # coding: utf-8 # # Plot street neworks and routes as interactive leaflet web maps # # Author: [Geoff Boeing](https://geoffboeing.com/) # # Use OSMnx to download a street network, calculate a route between two points, and create a Leaflet web map with folium. # # - [Overview of OSMnx](http://geoffboeing.com/2016/11/osmnx-python-street-networks/) # - [GitHub repo](https://github.com/gboeing/osmnx) # - [Examples, demos, tutorials](https://github.com/gboeing/osmnx-examples) # - [Documentation](https://osmnx.readthedocs.io/en/stable/) # - [Journal article/citation](http://geoffboeing.com/publications/osmnx-complex-street-networks/) # In[ ]: import networkx as nx import osmnx as ox from IPython.display import IFrame get_ipython().run_line_magic('matplotlib', 'inline') ox.config(log_console=True) ox.__version__ # In[ ]: # download the street network for Piedmont, CA G = ox.graph_from_place('Piedmont, California, USA', network_type='drive') # ## Plot a city's street network as an interactive web map # # You can pass keyword args along to [folium](https://python-visualization.github.io/folium/modules.html#folium.vector_layers.PolyLine) PolyLine to style the lines. # In[ ]: # plot the street network with folium m1 = ox.plot_graph_folium(G, popup_attribute='name', weight=2, color='#8b0000') # In[ ]: # 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. # ## Plot a route as an interactive web map # In[ ]: # 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) # In[ ]: # 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) # In[ ]: # save as html file then display map as an iframe filepath = 'data/route.html' m2.save(filepath) IFrame(filepath, width=600, height=500) # ## Or plot a route on top of the complete street network map # In[ ]: # 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) # In[ ]: # save as html file then display map as an iframe filepath = 'data/route_graph.html' m3.save(filepath) IFrame(filepath, width=600, height=500) # In[ ]: