osmnx计算地图两点最短路径返回相同节点问题修复
问题根源
ox.nearest_nodes接口参数顺序与旧版get_nearest_node不兼容:
- 旧版
get_nearest_node接收(纬度, 经度)格式的坐标 - 新版
nearest_nodes的参数签名为nearest_nodes(G, X, Y),其中X为经度、Y为纬度
替换接口时未调整参数顺序,传入坐标错位,导致起终点匹配到了错误的相同节点。
修复代码
将匹配节点的两行代码调整参数顺序,先传经度、后传纬度:
# 找起点最近节点:参数顺序为 图, 经度, 纬度 orig_node = ox.nearest_nodes(G, start_latlng[1], start_latlng[0]) # 找终点最近节点 dest_node = ox.nearest_nodes(G, end_latlng[1], end_latlng[0])
可选优化
- 最短路径计算建议去掉
method='bellman-ford'参数:OSM路网所有边权重均为正值,默认Dijkstra算法计算效率远高于Bellman-Ford。如果需要按实际行驶时间计算最短路径,可指定权重参数:shortest_route = nx.shortest_path(G, orig_node, dest_node, weight='travel_time') - 可通过绘图验证节点匹配正确性,标注起终点坐标位置:
fig, ax = ox.plot_graph_route(G, shortest_route, route_color='crimson', node_size=0, edge_linewidth=0.5) # 标注起点(绿色)、终点(蓝色),matplotlib坐标轴X为经度、Y为纬度 ax.scatter(start_latlng[1], start_latlng[0], c='limegreen', s=120, zorder=10, label='start') ax.scatter(end_latlng[1], end_latlng[0], c='royalblue', s=120, zorder=10, label='end') ax.legend()
内容的提问来源于stack exchange,提问作者Carola
相关产品推荐
相关产品推荐

