如何使用OSMNX提取type=route且route=bicycle的Relation类型数据?
提取OSMNX中OpenStreetMap的自行车路线(Relation类型)
你遇到的问题是ox.features_from_place默认不处理Relation类型的OSM要素,所以返回空结果。以下两种方法可以解决这个问题:
方法1:直接构造Overpass API查询获取Relation路线
OSMNX基于Overpass API,可以自定义查询语句来专门获取type=route且route=bicycle的Relation要素:
import osmnx as ox import geopandas as gpd # 目标区域 place = "Charente-Maritime" # 获取区域边界,用于限定查询范围 gdf_place = ox.geocode_to_gdf(place) bbox = gdf_place.total_bounds # 格式:(minx, miny, maxx, maxy) # 构造Overpass QL查询,指定获取Relation类型的自行车路线 overpass_query = f""" [out:json][timeout:60]; ( relation["route"="bicycle"]({bbox[1]}, {bbox[0]}, {bbox[3]}, {bbox[2]}); ); out body; >; out skel qt; """ # 执行查询并转换为GeoDataFrame response = ox.overpass_request(query=overpass_query) gdf_routes = ox.utils_geo._create_gdf(response, gdf_place.crs) # 查看结果 print(gdf_routes.shape) print(gdf_routes[["name", "route", "type"]].head())
方法2:提取Relation包含的道路(Way要素)
如果需要获取自行车路线对应的实际道路段,可以先提取Relation的成员Way ID,再查询这些道路:
# 从之前的响应中筛选出Relation要素 route_relations = [elem for elem in response["elements"] if elem["type"] == "relation"] # 收集所有属于自行车路线的Way ID way_ids = [] for rel in route_relations: way_ids.extend([mem["ref"] for mem in rel["members"] if mem["type"] == "way"]) # 查询这些Way对应的道路数据 ways_query = f""" [out:json][timeout:60]; ( way(id:{','.join(map(str, way_ids))}); ); out body; >; out skel qt; """ ways_response = ox.overpass_request(query=ways_query) gdf_ways = ox.utils_geo._create_gdf(ways_response, gdf_place.crs) # 查看道路结果 print(gdf_ways.shape)
关键说明
ox.features_from_place的设计主要针对Node和Way类型的要素,对Relation的支持不完善,因此需要直接调用Overpass API。- 查询语句中的
>; out skel qt;用于获取Relation包含的子要素(Way和Node),确保能生成完整的几何图形。
内容的提问来源于stack exchange,提问作者Cheesecake
相关产品推荐
相关产品推荐

