Travel time - Python

Viewed 558

Is there any way to calculate the minimum travel time from O-D route to point A, using Python and Google API or OSMnx library?

O and D refer to the Origin and Destination points, respectively.

For example:

O is (30.2641922, -97.746646)

D is (30.3034562, -97.7073463)

and A is a "stop" point (30.2903708, -97.7264791)

1 Answers

How about computing the distance of every node along the way and taking the shortest path? In the code below, I use a point A that is much closer since your point A is too far for me to store a graph that contains as many nodes as there are in between the path O-D and the point A. This solution will work for short distances but not for distances in your scale (~1000 miles).

import osmnx as ox
import numpy as np

origin      = (33.301821, -111.829871)
destination = (33.301402, -111.833108)
point_A     = (33.3003708, -111.8364791)

location_point = tuple(np.array([origin, destination, point_A]).mean(0))
G = ox.graph_from_point(location_point, dist=1000, truncate_by_edge=True)

origin_node = ox.distance.nearest_nodes(G, origin[1], origin[0])
destination_node = ox.distance.nearest_nodes(G, destination[1], destination[0])
point_A_node = ox.distance.nearest_nodes(G, point_A[1], point_A[0])


G = ox.add_edge_speeds(G, hwy_speeds = 100)
G = ox.add_edge_travel_times(G)

route = ox.shortest_path(G, origin_node, destination_node, weight="travel_time")

min_travel_time = np.inf
min_travel_node = None
for node in route:
    route_i = ox.shortest_path(G, node, point_A_node, weight="travel_time")
    travel_time = sum(ox.utils_graph.get_route_edge_attributes(G, route_i, "travel_time"))
    
Related