李祐齊
李祐齊

Reputation: 67

How can I get a shortest path on OpenStreetMap?

I've been working on finding shortest paths on OpenStreetMap. But some parts of the routes do not match the actual roads. As shown in the picture. The routes do not match the actual roads.Is there any way to fix this problem? Also, here are the codes:

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

Upvotes: 2

Views: 4044

Answers (1)

gboeing
gboeing

Reputation: 6442

You can do this with OSMnx. The following code snippet visualizes the route with folium while maintaining the curved street geometries:

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

Upvotes: 4

Related Questions