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

使用OSMnx计算两点步行距离:是否需追加节点距离及更优方案?

关于OSMnx计算步行距离的疑问

我现在用OSMnx计算城市里两点间的步行距离。因为OSMnx的shortest_path()函数只能算两个节点之间的距离(这些节点和实际点位可能有一段距离),所以我现在的做法是:把每个点位到最近节点的距离,加上shortest_path返回的节点间路径距离,以此得到两点间的总距离。

想问下这是不是最优方案?OSMnx有没有更简便的方法来计算两点间的步行距离(非直线距离)?

以下是参考函数代码:

def calculate_miles_between_two_points(G, loc_1, loc_2):
    '''Function is based on:
    https://github.com/gboeing/osmnx-examples/blob/main/notebooks/02-routing-speed-time.ipynb
    OSMnx is released under the MIT license by Geoff Boeing.
    This function is released under the MIT license by Kenneth Burchfiel.
    
    G is a networkx.classes.multidigraph.MultiDiGraph object 
    (e.g. one created by ox.graph_from_place()).
    loc_1 and loc_2 refer to tuples containing 
    latitude and longitude values in decimal degree form.
    Note that, if the distance between loc_1 and loc_2 is shorter than
    the sum of (1) the distance between each location and the node closest to it
    and (2) the sum of the distance between those two nodes,
    this function may report an inaccurately high distance.'''
    node_1, loc_1_dist_to_node_1 = ox.distance.nearest_nodes(G, X = loc_1[1], 
    Y = loc_1[0], return_dist=True)

    node_2, loc_2_dist_to_node_2 = ox.distance.nearest_nodes(G, X = loc_2[1], 
    Y = loc_2[0], return_dist = True)

    route = ox.shortest_path(G, node_1, node_2, weight = 'length') # Route is a list of nodes.
    # route
    edge_lengths = ox.utils_graph.get_route_edge_attributes(G, route, "length")
    route_in_miles = (sum(
        edge_lengths)+loc_1_dist_to_node_1+loc_2_dist_to_node_2)/1609.344 
        # There are 1609.344 meters in a mile.
    return route_in_miles

解答

你的方案是否最优?

你的思路可行,但不算最优——直接把点位到最近节点的直线距离加到路径长度里,会在某些场景下出现误差,比如两点本身距离极近,但各自最近节点的路径绕路时,总距离会被高估(正如你代码注释里提到的情况)。

OSMnx更简便的方法

OSMnx提供了更直接的工具来处理这个需求:

  1. 直接用坐标计算最短路径长度
    ox.routing.shortest_path_length()支持直接传入经纬度点位,内部会自动完成「找最近节点+计算节点间路径长度」的流程,无需手动处理节点匹配和距离累加,结果也更准确。

简化实现示例:

def calculate_walking_distance(G, loc1, loc2):
    # weight='length'对应步行路网的实际路径长度,method可选dijkstra/astar等算法
    distance_meters = ox.routing.shortest_path_length(G, loc1, loc2, weight='length', method='dijkstra')
    return distance_meters / 1609.344  # 转换为英里
  1. 同时获取路径与距离
    如果需要拿到具体路径,也可以直接给ox.routing.shortest_path()传经纬度,再计算路径总长度:
def get_walking_route_and_distance(G, loc1, loc2):
    route = ox.routing.shortest_path(G, loc1, loc2, weight='length')
    if not route:
        return None, 0.0
    edge_lengths = ox.utils_graph.get_route_edge_attributes(G, route, "length")
    total_miles = sum(edge_lengths) / 1609.344
    return route, total_miles

这些方法的优势:

  • 代码更简洁,无需手动调用nearest_nodes
  • 内部逻辑更贴合路网实际连接,避免直线距离累加的误差
  • 支持多种路由算法,可按需选择

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:05:35