如何使用OSMNX生成途经多个指定点的最短路径?寻求替代NetworkX分段实现的优雅方案
Great question! Yes, OSMnx (via its underlying NetworkX integration) fully supports multi-waypoint shortest path planning—and there are far cleaner, more scalable ways to implement this than manually stitching together individual segment paths like you’ve been doing.
Option 1: Optimized Chained Paths (Fixed Waypoint Order)
If you have a fixed sequence of waypoints (e.g., A → C → B), you can replace manual segment creation with a clean loop that handles any number of waypoints. This eliminates repetitive code and scales seamlessly if you add more stops later.
Here’s a concrete example:
import osmnx as ox import networkx as nx # Load your road network (adjust place/network type as needed) G = ox.graph_from_place("Portland, Oregon, USA", network_type="drive") # Define your waypoint sequence (start → waypoint 1 → ... → end) # Use (longitude, latitude) tuples, or node IDs if you already have them waypoints = [ (-122.6765, 45.5236), # Start point A (-122.6840, 45.5122), # Waypoint C (-122.7194, 45.5225) # End point B ] # Convert waypoints to their nearest nodes in the network nodes = [ox.distance.nearest_nodes(G, lon, lat) for lon, lat in waypoints] # Build the full path by chaining segments full_path = [] for u, v in zip(nodes[:-1], nodes[1:]): # Get shortest path for the current segment segment = nx.shortest_path(G, u, v, weight="length") # Add all nodes except the last one (to avoid duplicate nodes between segments) full_path.extend(segment[:-1]) # Add the final endpoint to complete the path full_path.append(nodes[-1]) # Visualize the result (optional) ox.plot_graph_route(G, full_path, route_color="#ff0000", route_linewidth=3)
Why this is better than your initial approach:
- Scalable: Works with 2, 5, or 20 waypoints without changing core logic
- DRY (Don’t Repeat Yourself): No manual copying of segment code for each stop
- Cleaner: Avoids redundant node entries where segments connect
Option 2: Global Shortest Path (Dynamic Waypoint Order)
If you don’t have a fixed order for your waypoints and want to find the shortest possible route that visits all stops (like a traveling salesman problem), you can use NetworkX’s approximation algorithms:
# Using the same G and nodes list from above # Find the shortest cycle that visits all nodes, then remove the duplicate start/end tsp_path = nx.approximation.traveling_salesman_problem(G, nodes, cycle=False) # Visualize the TSP route ox.plot_graph_route(G, tsp_path, route_color="#00ff00", route_linewidth=3)
Note: This gives you the optimal (or near-optimal) order of waypoints to minimize total distance, which is useful if your stop sequence isn’t predefined.
Key Notes
- OSMnx doesn’t have a dedicated "multi-waypoint path" function out of the box, but its tight integration with NetworkX means you can leverage all of NetworkX’s path-finding tools to build this functionality cleanly.
- Always use
weight="length"if you want shortest paths by distance; useweight="travel_time"if you’ve added speed data to your network (viaox.add_edge_speeds()andox.add_edge_travel_times()).
内容的提问来源于stack exchange,提问作者Luis




