python - Find shortest road(s) connecting any 2 pair of points
问题描述
I have a shapefile containing road network information and a list of lat lon points (shown in red in map). The points are not guaranteed to lie on a road.
I want to find the shortest road connecting any 2 pair of points and plot that road in a map. How can I do that?
The list of points (longitude, latitude) is as follows:
[[25.57925464 48.22272015]
[30.07394513 49.20624044]
[24.71950258 49.29032059]
[28.18076493 49.84160442]
[22.64412428 48.46259112]
[25.66738199 48.66065565]
[25.60755477 48.36588896]
[30.07236379 49.18836981]
[28.11408613 49.84760507]
[30.07152161 49.18863373]
[24.72089181 49.29014694]
[24.98422959 48.69505224]
[22.64554781 48.46238204]
[32.34790009 48.47251886]
[30.21000526 48.94404358]
[25.5806167 48.22461814]
[24.71188577 49.29464777]
[30.07581965 49.20389477]
[30.07527381 49.18857539]
[31.36285513 49.3070935 ]
[32.34209481 48.4793055 ]
[28.68966268 49.13953097]
[28.11572736 49.84822564]
[31.1910739 48.59072315]
[26.8153163 48.85545504]
[25.6630429 48.34444028]
[24.89757249 48.7625933 ]
[24.71154061 49.29478723]
[25.6682908 48.66009589]
[25.66472488 48.6610783 ]
[31.37621921 49.32160973]
[32.39707855 51.24104624]
[31.3429478 51.11037809]
[28.69020289 49.13702762]
[25.66292554 48.34328093]
[28.70593533 49.11971917]
[25.66954126 48.659588 ]
[31.7971185 48.21618349]
[32.32701329 48.46917026]
[28.03302836 49.33822554]
[24.89234006 48.76446997]
[26.81222988 48.8546306 ]
[25.60984975 48.36571544]
[28.02327843 49.33662326]
[24.98381373 48.69454483]
[30.21105788 48.94595284]
[31.36002599 49.32395471]
[28.70703167 49.11916411]
[32.3266258 48.46759114]
[28.11179067 49.8483458 ]
[31.19093051 48.58989204]
[32.33653923 48.47028404]]
解决方案
import osmnx as ox
list_coords = [(25.57925464 48.22272015),(30.07394513 49.20624044)]
p1 = list_coords[0]
p2 = list_coords[1]
import geopandas
gdf_nodes = geopandas.read_file('nodes.shp') #shapefiles that you have
gdf_edges = geopandas.read_file('edges.shp') #shapefiles that you have
G = ox.gdfs_to_graph(gdf_nodes, gdf_edges)
node1 = ox.get_nearest_node(G,p1) #to get node on the graph nearest to the point p1
node2 = ox.get_nearest_node(G,p2) #to get node on the graph nearest to the point p2
import networkx as nx
route = nx.shortest_path(G, node1, node2, weight='length') #obtain shortest path based on length
route_length = nx.shortest_path_length(G, node1, node2, weight='length') #obtain shortest path length