Skip to content Skip to sidebar Skip to footer

Shortest Route When Converted To Linestring Misses The Path In Osmnx

I'm trying to save the route to the disk which i plotted using OSMNX. The route generated follows the road path but, when i try to convert the path to LineString which I can easily

Solution 1:

This will save your OSMnx shortest path route as a LineString geometry in a shapefile:

import geopandas as gpd
import networkx as nx
import osmnx as ox
from shapely.geometry import LineString, MultiLineString
ox.config(log_console=True, use_cache=True)

orig = (13.013206, 77.670987)
dest = (12.821339, 77.678500)
G = ox.graph_from_point(orig, dist=10000, dist_type='network', network_type='drive')
orig_node  = ox.get_nearest_node(G, orig)
dest_node  = ox.get_nearest_node(G, dest)

# impute edge speeds, add travel times, calculate shortest path
G = ox.add_edge_speeds(G)
G = ox.add_edge_travel_times(G)
route = nx.shortest_path(G, orig_node, dest_node, weight='travel_time')

# OPTION 1: save node-to-node straightline route as shapefile
nodes, edges = ox.graph_to_gdfs(G)
route_nodes = nodes.loc[route]
route_line = LineString(route_nodes['geometry'].tolist())
gdf1 = gpd.GeoDataFrame(geometry=[route_line], crs=ox.settings.default_crs)
gdf1.to_file('route1')

# OPTION 2: save route edge geometries as shapefile
edges = edges.set_index(['u', 'v', 'key'])
geoms = [edges.loc[(u, v, 0), 'geometry'] for u, v in zip(route[:-1], route[1:])]
gdf2 = gpd.GeoDataFrame(geometry=[MultiLineString(geoms)], crs=ox.settings.default_crs)
gdf2.to_file('route2')

Post a Comment for "Shortest Route When Converted To Linestring Misses The Path In Osmnx"