如何使用Python NetworkX获取最短路径的几何图形?
获取最短路径几何图形的实现方法
要提取最短路径的实际几何图形,你需要先获取路径对应的节点序列,再映射到edges中的对应边,最后合并几何形状。具体步骤和代码修改如下:
核心步骤
- 用
nx.shortest_path()获取完整的节点序列(替代仅返回长度的nx.shortest_path_length()) - 将节点序列转换为边的唯一标识元组(
u, v, key) - 从edges GeoDataFrame中筛选出路径对应的边
- 合并边的几何图形得到连续的完整路径
修改后的完整代码
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
相关产品推荐
相关产品推荐

