Search code examples
pythonnetworkxgeopandasshortest-pathosmnx

calculate route and arrival time between two point in python


i have two simple point(lat,lon) and one parameter named speed. i need to find the route and arrival time.

for example:

point1: (1,1)   
point2: (5,5)   
speed: x km/h
one possible route is : (1,1) -> (2,2) -> (3,3) -> (4,4) -> (5,5)

now i also need the arrival time to each point in route. something like this:

[(1,1),0:00] -> [(2,2),1:00] -> [(3,3),2:00] -> [(4,4),3:00] -> [(5,5),4:00]   

first element shows point and second shows arrival time (or time spent to reach that point or any other value that shows time to reach that point)

one important thing is that i want to run this on real-world map so then the lat and lng will be used from the world map.


so ... i did this:

import osmnx as ox
import networkx as nx
ox.settings.log_console=True
ox.settings.use_cache=True


start_latlng = (35.73509, 51.4171)
end_latlng = (35.73674, 51.40611)
mode      = 'walk'
optimizer = 'time'

graph = ox.graph_from_place('tehran', network_type = mode)
orig_node = ox.distance.nearest_nodes(graph, start_latlng[1],start_latlng[0])
dest_node = ox.distance.nearest_nodes(graph, end_latlng[1],end_latlng[0])

shortest_route = nx.shortest_path(graph,
                                orig_node,
                                dest_node,
                                weight=optimizer)


print(shortest_route)

the result was this:

[1649103291, 717069600, 1922773706, 423733650, 4444063663, 3376783364, 2178480086, 2178480071, 2179951182, 1880160160, 3429927627, 3856787096, 3856787099, 436153557, 1649103461, 29004286, 423746569]

1- the problem with this is that i don't know what are these numbers mean? i know i can plot them but i need lat, lng not this!

2- second i don't know the arrival time to each point. i mean how much does it take to travel from starting point to other point.

3- it is so slow ! i need too faster approach.

so how can i get results like this?

[(1,1),0:00] -> [(2,2),1:00] -> [(3,3),2:00] -> [(4,4),3:00] -> [(5,5),4:00]   

Solution

  • Your shortest_route must be the sequence of the nodes ID (from your graph) you must visit to go from orig_node to dest_node using the shortest path. You probably have in the graph object a correspondance between the node ID and a (lat, lng) tuple.

    Once you have your (lat, lng) sequence, you will be able to determine the arrival time at each point by first computing the distance between each couple of points and then deducing the travel time using your mean speed. You can compute the great-circle distance between two points using the haversine formula (this assume that Earth is a perfect sphere) or even better, compute the geodesic distance (this assume that Earth is an ellipsoid, so closer to reality).

    The GeoPy package offers methods to compute both easily.