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

OSMnx无法加载路网图求助:运行代码出现Shapely警告

解决OSMnx调用graph_from_place时的Shapely RuntimeWarning问题

问题场景

我尝试用Python的OSMnx库计算两点间驾驶距离,运行以下代码:

import osmnx as ox

G = ox.graph_from_place("Piedmont, California, USA", network_type="drive")

但运行时弹出一系列Shapely相关的RuntimeWarning:

/Users/luismoncayo/anaconda3/envs/Hope/lib/python3.11/site-packages/shapely/constructive.py:181: RuntimeWarning: invalid value encountered in buffer
  return lib.buffer(
/Users/luismoncayo/anaconda3/envs/Hope/lib/python3.11/site-packages/shapely/predicates.py:798: RuntimeWarning: invalid value encountered in intersects
  return lib.intersects(a, b, **kwargs)
/Users/luismoncayo/anaconda3/envs/Hope/lib/python3.11/site-packages/shapely/set_operations.py:340: RuntimeWarning: invalid value encountered in union
  return lib.union(a, b, **kwargs)
/Users/luismoncayo/anaconda3/envs/Hope/lib/python3.11/site-packages/shapely/predicates.py:798: RuntimeWarning: invalid value encountered in intersects
  return lib.intersects(a, b, **kwargs)
/Users/luismoncayo/anaconda3/envs/Hope/lib/python3.11/site-packages/shapely/set_operations.py:340: RuntimeWarning: invalid value encountered in union
  return lib.union(a, b, **kwargs)

解决方法

  • 更新依赖库版本:这类警告多由Shapely、OSMnx或Geopandas版本不兼容导致,先升级相关依赖:

    pip install --upgrade osmnx shapely geopandas
    
  • 改用边界多边形生成路网:跳过地名解析的几何计算步骤,直接用目标区域的边界多边形生成图:

    import osmnx as ox
    
    # 获取Piedmont的边界数据
    place_gdf = ox.geocode_to_gdf("Piedmont, California, USA")
    # 基于边界多边形生成驾驶路网
    G = ox.graph_from_polygon(place_gdf.geometry.iloc[0], network_type="drive")
    
  • 临时屏蔽警告:确认功能不受影响的前提下,可在代码开头添加警告过滤:

    import warnings
    warnings.filterwarnings("ignore", category=RuntimeWarning)
    
    import osmnx as ox
    G = ox.graph_from_place("Piedmont, California, USA", network_type="drive")
    
  • 清理OSMnx缓存:若本地缓存的OSM数据损坏,删除缓存目录后重新获取数据。Mac/Linux缓存路径为~/.osmnx,Windows路径为C:\Users\<你的用户名>\.osmnx。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:48:26