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

如何通过OSMnx获取路线中高速公路的南北方向?

如何通过OSMnx判断高速公路行驶方向(北行/南行)

问题场景

使用OSMnx进行路径规划时,需要确定路线中某段高速公路(如示例中的I-110 Harbor Freeway)是北行还是南行。现有代码输出的路段属性中,reversed字段仅表示图中路段方向与OpenStreetMap(OSM)原始数据是否一致,但无法直接对应南北方向,因此需要更直观的判断方法。

示例代码

import osmnx as ox
import networkx as nx

G = ox.graph_from_place("Los Angeles County, California, USA", network_type="drive")

origin = (33.821642, -118.281422)
destination = (33.876752, -118.055168)
origin_node = ox.distance.nearest_nodes(G, origin[1], origin[0])
destination_node = ox.distance.nearest_nodes(G, destination[1], destination[0])
route = ox.shortest_path(G, origin_node, destination_node, weight="travel_time")
fig, ax = ox.plot_graph_route(G, route, route_color="c", node_size=0)

# 查看第9段路段的属性(索引从0开始)
print(G.edges[(route[8], route[9], 0)])

路段属性输出

{'osmid': [604115924, 604115927],
'oneway': True,
'lanes': '4',
'ref': 'I 110',
'name': 'Harbor Freeway',
'highway': 'motorway',
'reversed': False,
'length': 1232.397,
'geometry': <LINESTRING (-118.287 33.831, -118.287 33.836, -118.287 33.837, -118.287 33....>}

解决方案

直接通过路段的坐标变化判断南北方向,这是最可靠的方法,无需依赖reversed字段的模糊定义。

方法一:通过节点坐标判断

OSMnx的图节点包含经纬度信息(y为纬度,x为经度),纬度值越大表示位置越靠北。对比路段起点和终点节点的纬度即可判断方向:

# 提取路段的起点和终点节点
start_node = route[8]
end_node = route[9]

# 获取节点的纬度值
start_lat = G.nodes[start_node]['y']
end_lat = G.nodes[end_node]['y']

# 判断行驶方向
if end_lat > start_lat:
    print("该路段为I-110北行线")
else:
    print("该路段为I-110南行线")

方法二:通过路段几何坐标判断

路段的geometry字段包含完整的路径坐标序列,对比首尾坐标的纬度值也能得到方向:

# 提取路段的几何信息
geom = G.edges[(route[8], route[9], 0)]['geometry']

# 获取路径的第一个和最后一个坐标点(格式为(经度, 纬度))
first_coord = list(geom.coords)[0]
last_coord = list(geom.coords)[-1]

# 对比纬度值判断方向
if last_coord[1] > first_coord[1]:
    print("该路段为I-110北行线")
else:
    print("该路段为I-110南行线")

说明

  • OSM原始数据的道路方向不一定按南北走向定义,可能由绘制顺序或其他规则决定,因此reversed字段无法直接对应南北方向。
  • 示例中路段的坐标纬度从33.831逐渐升高到33.837+,说明是向北行驶,即I-110北行线。

内容的提问来源于stack exchange,提问作者Z. G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:23:24