OSMNX中纽约市路网图无法匹配指定坐标节点的问题
问题原因及修复方案
错误根源
你调用ox.distance.nearest_nodes时加了return_dist=True,这个参数会让函数返回**(节点ID, 该点到节点的距离)**的元组,而不是单纯的节点ID。你直接把这个元组传给ox.shortest_path,函数会把元组当作节点ID去图里查找,肯定找不到对应的节点,所以抛出NodeNotFound错误。
修复步骤
- 从返回的元组中提取第一个元素(也就是节点ID),舍弃距离值
- (可选)用OSMNX内置方法计算行程时间,比手动求和更简洁
修正后的完整代码
import osmnx as ox # 下载纽约市驾车路网图 G = ox.graph_from_place('New York City', network_type='drive', simplify=True) # 起点和终点坐标(注意:nearest_nodes的参数顺序是lon, lat,已调整正确顺序) orig_lat = 40.6662 orig_lon = -73.9340 dest_lat = 40.6576 dest_lon = -73.9208 # 查找最近节点,提取节点ID orig_node, orig_dist = ox.distance.nearest_nodes(G, orig_lon, orig_lat, return_dist=True) dest_node, dest_dist = ox.distance.nearest_nodes(G, dest_lon, dest_lat, return_dist=True) print(f"Origin node: {orig_node}, 距离起点: {orig_dist}米") print(f"Destination node: {dest_node}, 距离终点: {dest_dist}米") # 计算最短路径 route = ox.shortest_path(G, orig_node, dest_node, weight='length') # 用OSMNX内置方法计算行程时间(基于默认道路速度) travel_time = ox.utils_graph.route_to_gdf(G, route, edge_attrs=['length', 'travel_time'])['travel_time'].sum() print(f"Travel time (seconds): {travel_time}") # 如果坚持手动计算,修正后的写法: # travel_secs = sum(G[u][v][0]['length'] for u, v in zip(route[:-1], route[1:])) / (1000/3600) / 2.23694 # 转换为秒 # print(f"Travel time (seconds): {travel_secs}")
额外注意点
ox.distance.nearest_nodes的参数顺序是经度(lon), 纬度(lat),你原来的代码把lat放在前面,逻辑上有误,修正代码里已调整- OSMNX内置了
travel_time属性(基于道路类型默认速度),直接用route_to_gdf提取求和更高效准确
内容的提问来源于stack exchange,提问作者Thales Protopapas
相关产品推荐
相关产品推荐

