'Is there any way to create the shortest path going through multiple (more than 2) different points using OSMNX?

I was wondering if there was a way to get the shortest path between an origin and a target, but with the path going through different points defined along the way (we could consider them stops, for example, going from A to B but going through C).

For a first approximation I have been using the shortest_path of networkx. I have created as many routes as points I have, using each target as the origin of the next route. But I want to know if there was an easier and more elegant way to do it.



Solution 1:[1]

You can just chain the trips together:

import osmnx as ox
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')

point1 = list(G.nodes)[0]
point2 = list(G.nodes)[100]
point3 = list(G.nodes)[200]

path1 = ox.shortest_path(G, point1, point2)
path2 = ox.shortest_path(G, point2, point3)
path = path1 + path2[1:]

Or, to generalize the problem, if you want to solve a path between multiple nodes (visiting an arbitrary number of nodes along the way):

import numpy as np
import osmnx as ox

# use a strongly connected graph so all paths are solvable
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')
G = ox.utils_graph.get_largest_component(G, strongly=True)

# get some random nodes to visit
rands = np.linspace(0, len(G.nodes), num=100, endpoint=False)
nodes = [list(G.nodes)[int(rand)] for rand in rands]

# solve path from 1st node to 2nd node to... nth node
path = list()
for orig, dest in zip(nodes[:-1], nodes[1:]):
    path = path[:-1] + ox.shortest_path(G, orig, dest, weight='length')
fig, ax = ox.plot_graph_route(G, path, node_size=0, route_alpha=0.5)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gboeing