DAY 20
0
AI & Data

## Day20 OSMnx應用

OSMnx除了介接了Overpass API，可以透過python方便的取得OpenStreetMap的圖資以外，它還提供了一些路網相關的分析方法，這些方法主要是來自networkX。

• 計算最短路徑
• 服務範圍、等時圈

## 計算最短路徑

``````import osmnx as ox
G = ox.graph_from_point((25.048545,121.51123), distance=3000, network_type='drive')
ox.plot_graph(G)
``````

``````origin = ox.get_nearest_node(G, (25.049545,121.5599))
destination = ox.get_nearest_node(G, (25.048545,121.51123))
``````

``````import networkx as nx
route = nx.shortest_path(G, origin, destination)
ox.plot_graph_route(G, route)
``````

## 服務範圍、等時圈

``````import osmnx as ox
G = ox.graph_from_point((25.048545,121.51123), distance=2000, network_type='drive')
ox.plot_graph(G)
G = ox.project_graph(G) # 投影
``````

``````center_node = ox.get_nearest_node(G, (25.048545,121.51123))
``````

``````meters_per_minute = 10 * 1000 / 60 # 每小時10公里
for u, v, k, data in G.edges(data=True, keys=True):
data['time'] = data['length'] / meters_per_minute
``````

``````import networkx as nx
trip_times = [5, 8, 12] #分鐘
# 給定顏色
iso_colors = ox.get_colors(n=len(trip_times), cmap='Reds', start=0.3, return_hex=True)
node_colors = {}
for trip_time, color in zip(sorted(trip_times, reverse=True), iso_colors):
subgraph = nx.ego_graph(G, center_node, radius=trip_time, distance='time')
for node in subgraph.nodes():
node_colors[node] = color # 抵達的node給顏色
``````

``````nc = [node_colors[node] if node in node_colors else 'none' for node in G.nodes()]
ns = [20 if node in node_colors else 0 for node in G.nodes()]
fig, ax = ox.plot_graph(G, fig_height=8, node_color=nc, node_size=ns, node_alpha=0.8, node_zorder=2)
``````