如何在OpenStreetMap上获取最短路径?

2024-05-14 05:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在OpenStreetMap上寻找最短路径。但部分路线与实际道路不符。如图所示The routes do not match the actual roads.有没有办法解决这个问题?此外,以下是代码:

import osmnx as ox
import networkx as nx
import folium

lat = [-33.889606, -33.889927, -33.889155, -33.891134]
lon = [151.283306, 151.280497, 151.278007, 151.274453]

fmap = folium.Map(location=[-33.889606, 151.283306], zoom_start=15)
colors=["red", "yellow", "green"]

for i in range(3):
    G = ox.graph_from_point((-33.889606, 151.283306), distance=4000,network_type='drive')
    a = ox.get_nearest_node(G, (lat[i], lon[i]))
    b = ox.get_nearest_node(G, (lat[i+1], lon[i+1]))
    route = nx.shortest_path(G, a, b)
    gdf_nodes, gdf_edges = ox.graph_to_gdfs(G)
    latitude = gdf_nodes.loc[route].y
    longitude = gdf_nodes.loc[route].x

    latitude = latitude.values
    longitude = longitude.values

    latitude=latitude.tolist()
    longitude=longitude.tolist()

    coordinate=[]
    for j in range(len(latitude)):
        coordinate.append([latitude[j],longitude[j]])
    fmap.add_child(folium.PolyLine(locations=coordinate, weight=5, color=colors[i]))

fmap

Tags: importcoordinateasrouteoxnodesloncolors
1条回答
网友
1楼 · 发布于 2024-05-14 05:35:40

您可以使用OSMnx执行此操作。下面的代码段在保持弯曲街道几何图形的同时,使用folium可视化路线:

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

# get a graph
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')

# impute missing edge speed and add travel times
G = ox.add_edge_speeds(G)
G = ox.add_edge_travel_times(G)

# calculate shortest path minimizing travel time
orig, dest = list(G)[0], list(G)[-1]
route = nx.shortest_path(G, orig, dest, 'travel_time')

# create folium web map
route_map = ox.plot_route_folium(G, route)
route_map

enter image description here

相关问题 更多 >