Solve k shortest paths from an origin node to a destination node.
See also shortest_path to get just the one shortest path.
# OSMnx: New Methods for Acquiring, Constructing, Analyzing, and Visualizing Complex Street Networks
import osmnx as ox
ox.config(use_cache=True, log_console=False)
ox.__version__
'1.1.2'
center_point = (37.5661, 126.9783) # (lat, lng) Seoul, South Korea
dist = 1000
dist_type = 'bbox' # "network", "bbox"
network_type = 'drive' # "all_private", "all", "bike", "drive", "drive_service", "walk"
# Create a graph from OSM within some distance of some (lat, lng) point.
G = ox.graph_from_point(
center_point,
dist=dist,
dist_type=dist_type,
network_type=network_type)
# Plot a graph.
fig, ax = ox.plot_graph(G)
# Set origin and destination node ID
orig = list(G)[0]
dest = list(G)[-1]
# Solve k shortest paths from an origin node to a destination node.
# k (int) – number of shortest paths to solve
paths = ox.k_shortest_paths(G, orig, dest, k=2, weight='length')
# routes as a list of lists of node IDs
route = list(paths)
# Plot several routes along a graph.
fig, ax = ox.plot_graph_routes(G, route, route_colors=['r', 'y'])
import random
# Solve k shortest paths from an origin node to a destination node.
# k (int) – number of shortest paths to solve
paths = ox.k_shortest_paths(G, orig, dest, k=2, weight='travel_time')
# routes as a list of lists of node IDs
route = list(paths)
# get node colors by linearly mapping an attribute's values to a colormap
route_colors = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(len(route))]
# Plot several routes along a graph.
fig, ax = ox.plot_graph_routes(G, route, route_colors=route_colors)