You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python NetworkX获取最短路径的几何图形?

获取最短路径几何图形的实现方法

要提取最短路径的实际几何图形,你需要先获取路径对应的节点序列,再映射到edges中的对应边,最后合并几何形状。具体步骤和代码修改如下:

核心步骤

  1. 用nx.shortest_path()获取完整的节点序列(替代仅返回长度的nx.shortest_path_length())
  2. 将节点序列转换为边的唯一标识元组(u, v, key)
  3. 从edges GeoDataFrame中筛选出路径对应的边
  4. 合并边的几何图形得到连续的完整路径

修改后的完整代码

import osmnx as ox
import networkx as nx
from shapely.geometry import Point, LineString
import geopandas as gpd

def get_network(centre_point, dist):
    G = ox.graph_from_point(centre_point, dist=dist, network_type='walk', simplify=False)
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_travel_times(G)
    nodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)
    return G, nodes, edges


point = (50.864595387190924, -2.153190840083006)
G, nodes, edges = get_network(centre_point=point, dist=1000)

a = nodes.iloc[4].name
b = nodes.iloc[20].name

# 1. 获取最短路径的节点序列
path_nodes = nx.shortest_path(G, a, b, weight='length', method='dijkstra')

# 2. 生成路径对应边的元组列表(兼容平行边场景)
path_edges = []
for u, v in zip(path_nodes[:-1], path_nodes[1:]):
    # 遍历所有可能的平行边key
    for key in G[u][v]:
        path_edges.append((u, v, key))

# 3. 从edges中筛选出路径边
path_gdf = edges.loc[path_edges]

# 4. 合并边的几何得到完整路径
path_geometry = LineString([coord for line in path_gdf['geometry'] for coord in line.coords])

# 可选:转为GeoDataFrame方便后续处理/可视化
path_full_gdf = gpd.GeoDataFrame({'geometry': [path_geometry]}, crs=edges.crs)

关键说明

  • 如果你的图启用了simplify=True,通常不会有平行边,可直接用path_edges.append((u, v, 0))简化代码
  • 合并后的path_geometry是连续的LineString对象,可直接用于可视化、空间分析等场景
  • path_full_gdf保留了原坐标系,能和nodes、edges等地理数据无缝联动

内容的提问来源于stack exchange,提问作者Spatial Digger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 05:10:23