Find Shortest Path Using Python OSMnx Routing Module
Last Updated :
18 Mar, 2024
This article demonstrates how to use the OSMnx routing module to find the shortest path, illustrated with practical examples.
Syntax of osmnx.routing.shortest_path() Function
OSMnx routing module has the 'shortest_path' functionality to find the nearest path from the origin node to the destination node. The function is as follows:
osmnx.routing.shortest_path(G, orig, dest, weight='length', cpus=1)
Parameters:
- G (networkx.MultiDiGraph) – input graph
- orig (int or list) – origin node ID, or a list of origin node IDs
- dest (int or list) – destination node ID, or a list of destination node IDs
- weight (string) – edge attribute to minimize when solving shortest path
- cpus (int) – how many CPU cores to use; if None, use all available. It allows parallel processing but make sure not to exceed the available RAM
Returns: path – list of node IDs constituting the shortest path, or, if orig and dest are lists, then a list of path lists
Return Type: List
The shortest_path functionality make use of Dijkstra's shortest path algorithm to find the shortest path between the origin node and destination node.
Find Shortest Path Using Python OSMnx Routing Module
Let's implement the functionality to find the shortest path. As a first step we need to get the origin node and destination node. We make use of Thiruvanathapuram city data using osmnx and fetch the origin and destination node w.r.t Kazhakkootam and Medical College respectively. The code as follows:
Python3
import osmnx as ox
# load thiruvananthapuram city
place = "Thiruvananthapuram, Kerala"
G = ox.graph_from_place(place, network_type="drive")
# kazhakootam coordinates
kzh_lat, kzh_lon = 8.5686, 76.8731
# medical college coordinates
mdcl_lat, mdcl_lon = 8.52202892500963, 76.926448394559
# fetch the nearest node w.r.t coordinates
kzh_node = ox.distance.nearest_nodes(G, kzh_lon, kzh_lat)
mdcl_node = ox.distance.nearest_nodes(G, mdcl_lon, mdcl_lat)
print("Kazhakkottam Node: {kzh_node}, \
Medical College Node: {mdcl_node}".format(
kzh_node=kzh_node, mdcl_node=mdcl_node))
Output:
Kazhakkottam Node: 1141007999, Medical College Node: 9992653265
Now we have the nodes. Let's calculate the shortest distance form Kazhakootam node (origin node) to Medical College node(destination node). The code as shown below:
Python3
import osmnx as ox
place = "Thiruvananthapuram, Kerala"
G = ox.graph_from_place(place, network_type="drive")
# orgin node and destination node
orig, dest = 1141007999, 9992653265
# find shortest path
route_nodes = ox.routing.shortest_path(G, orig, dest, weight="length")
# plot the shortes path
fig, ax = ox.plot_graph_route(G, route_nodes, route_color="r",
route_linewidth=6, node_size=0)
Output:
shortest path plotLet's plot it on map. We have to reconstruct the edges (u, v, k) based on the shortest route generated from above code. Fetch the graph edges from our multidigraph based on the constructed edges. The graph edges are multiindexed with (u, v, k) params. The code as follows:
Python3
def generate_multindex(route_nodes):
multiindex_list = []
# append the index to list
for u, v in zip(route_nodes[:-1], route_nodes[1:]):
multiindex_list.append((u, v, 0))
return multiindex_list
# get edges from from above multidigraph
gdf_nodes, gdf_edges = ox.graph_to_gdfs(G)
# generate multiindex based on generated shortest route
multiindex_list = generate_multindex(route_nodes)
# fetch edge details based on multi index list
shrt_gdf_edges = gdf_edges[gdf_edges.index.isin(multiindex_list)]
# plot the shortest route on map
shrt_gdf_edges.explore(color="red")
Output:
The path in red color depicts the shortest path from Kazhakkottam to Medical Colledge.
shortest path
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read