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

如何用OSMnx获取两点间精准最短路径?附坐标与代码示例

解决OSMnx获取精准最短路径的问题

看起来你遇到的问题是get_nearest_node返回的节点偏离了理想路径的起点/终点,导致生成的红色路径和预期的黑色路径不符。这是因为get_nearest_node只会返回距离输入坐标最近的路网节点,但你的目标起点/终点可能位于两条节点之间的边上,而非节点本身,所以会出现绕路的情况。

下面是两种可行的解决方案,帮你获取更精准的最短路径:

方法1:直接使用ox.shortest_path传入坐标(推荐)

OSMnx的shortest_path函数支持直接传入经纬度坐标对作为起点和终点,它会自动处理坐标到路网边的投影,而不是强制绑定到最近的节点,能更精准地匹配你的理想路径起点/终点。

修改后的代码如下:

import folium
import osmnx as ox
import networkx as nx

ox.config(use_cache=True, log_console=True)

# 定义你的起点和终点坐标
orig_point = (-33.889606, 151.283306)
dest_point = (-33.889927, 151.280497)

# 获取指定范围内的驾车路网
G = ox.graph_from_point(orig_point, dist=3000, network_type='drive')
G = ox.speed.add_edge_speeds(G)
G = ox.speed.add_edge_travel_times(G)

# 直接传入坐标计算最短路径,weight用travel_time保证时间最短(或用length保证距离最短)
route = ox.shortest_path(G, orig_point, dest_point, weight='travel_time')

# 绘制并保存路径地图
route_map = ox.plot_route_folium(G, route)
route_map.save('test.html')

方法2:手动投影坐标到路网边(进阶)

如果方法1的结果仍不理想,你可以手动将坐标投影到对应的路网边上,精准定位起点/终点的位置:

import folium
import osmnx as ox
import networkx as nx

ox.config(use_cache=True, log_console=True)

orig_point = (-33.889606, 151.283306)
dest_point = (-33.889927, 151.280497)

G = ox.graph_from_point(orig_point, dist=3000, network_type='drive')
G = ox.speed.add_edge_speeds(G)
G = ox.speed.add_edge_travel_times(G)

# 获取起点和终点所在的最近路网边
orig_edge = ox.get_nearest_edge(G, orig_point)
dest_edge = ox.get_nearest_edge(G, dest_point)

# 将坐标投影到对应边上,得到投影后的精确点位信息
orig_proj = ox.distance.project_onto_edge(G, orig_point, orig_edge)
dest_proj = ox.distance.project_onto_edge(G, dest_point, dest_edge)

# 从投影结果中提取边的节点信息和投影点
orig_u, orig_v, _, _, _, orig_proj_point = orig_proj
dest_u, dest_v, _, _, _, dest_proj_point = dest_proj

# 基于投影后的位置计算最短路径(这里仍可使用ox.shortest_path传入投影点坐标)
route = ox.shortest_path(G, orig_proj_point, dest_proj_point, weight='travel_time')

route_map = ox.plot_route_folium(G, route)
route_map.save('test.html')

额外检查点

如果以上方法都没得到理想的黑色路径,建议先检查:

  • 你指定的network_type='drive'是否正确?如果理想路径是步行/骑行专用路,需要改为对应的类型(如'walk'/'bike')
  • 调用ox.plot_graph(G)查看获取的路网,确认理想路径是否被OSM数据收录——如果路网本身没有这条路径,工具自然无法生成

内容的提问来源于stack exchange,提问作者李祐齊

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:07:38