如何使用 OSMnx 从 OSM 格式的 XML 文件创建过滤图?

How to create a filtered graph from an OSM-formatted XML file using OSMnx?

在Python中,我们可以使用一个函数osmnx.graph_from_place()和一个过滤器custom_filter='["waterway"="river"]'来得到过滤后的图形。

import osmnx as ox
G = ox.graph_from_place("isle of man", custom_filter='["waterway"="river"]') # download directly.
fig, ax = ox.plot_graph(G, node_color='r')

我想从磁盘中的 OSM 格式 XML 文件中获取过滤图,但函数 osmnx.graph_from_xml() 不支持参数 custom_filter。如何从 *.osm 数据中获取过滤图?

这将绘制整个 *.osm 数据集:

import osmnx as ox
G = ox.graph_from_xml("isle-of-man-latest.osm") # from disk.
fig, ax = ox.plot_graph(G, node_color='r')

OSMnx 的 custom_filter 参数允许您使用 OverpassQL 过滤 Overpass 查询,以生成用于图形构建的过滤原始数据。如果您正在加载 .osm 文件,那么您将明确绕过 Overpass 查询步骤,而是直接导入原始数据的本地文件以构建图形。 OSMnx 根据您提供的任何原始数据构建图表。

你有几个选择。首先,如果可能,您可以直接使用 OSMnx 的 graph_from_placegraph_from_polygon 函数来获取图形,而不是从 .osm 文件加载。二、如果需要用到graph_from_xml,又想过滤,构造好后过滤即可:

import osmnx as ox
ox.config(use_cache=True, log_console=True)

# create a graph with more edges than you want
G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive', simplify=False)

# filter graph to retain only certain edge types
filtr = ['tertiary', 'tertiary_link', 'secondary', 'unclassified']
e = [(u, v, k) for u, v, k, d in G.edges(keys=True, data=True) if d['highway'] not in filtr]
G.remove_edges_from(e)

# remove any now-disconnected nodes or subcomponents, then simplify toplogy
G = ox.utils_graph.get_largest_component(G)
G = ox.simplify_graph(G)