0

I am using OSMnx to calculate the walking distance between two points in a city. Since OSMnx's shortest_path() function calculates the distance between two nodes (which may be some distance from the actual points), I am adding the distance between each point and its nearest node to the distance returned by shortest_path in order to calculate the total distance between those two points.

Is this the best approach, or does OSMnx have a simpler means to determine the walking distance (not the straight-line distance) between two points?

Here is my function for reference:

def calculate_miles_between_two_points(G, loc_1, loc_2):
    '''Function is based on:
    https://github.com/gboeing/osmnx-examples/blob/main/notebooks/02-routing-speed-time.ipynb
    OSMnx is released under the MIT license by Geoff Boeing.
    This function is released under the MIT license by Kenneth Burchfiel.
    
    G is a networkx.classes.multidigraph.MultiDiGraph object 
    (e.g. one created by ox.graph_from_place()).
    loc_1 and loc_2 refer to tuples containing 
    latitude and longitude values in decimal degree form.
    Note that, if the distance between loc_1 and loc_2 is shorter than
    the sum of (1) the distance between each location and the node closest to it
    and (2) the sum of the distance between those two nodes,
    this function may report an inaccurately high distance.'''
    node_1, loc_1_dist_to_node_1 = ox.distance.nearest_nodes(G, X = loc_1[1], 
    Y = loc_1[0], return_dist=True)

    node_2, loc_2_dist_to_node_2 = ox.distance.nearest_nodes(G, X = loc_2[1], 
    Y = loc_2[0], return_dist = True)

    route = ox.shortest_path(G, node_1, node_2, weight = 'length') # Route is a list of nodes.
    # route
    edge_lengths = ox.utils_graph.get_route_edge_attributes(G, route, "length")
    route_in_miles = (sum(
        edge_lengths)+loc_1_dist_to_node_1+loc_2_dist_to_node_2)/1609.344 
        # There are 1609.344 meters in a mile.
    return route_in_miles

KBurchfiel
  • 635
  • 6
  • 15
  • 2
    Adding the point-node distance to the path length is probably the easiest method. – gboeing Mar 30 '23 at 00:51
  • 1
    I gave an answer by updating my post here: https://stackoverflow.com/questions/36994746/how-to-find-path-and-distance-between-two-coordinates-using-osm-and-python – Rivers Apr 07 '23 at 16:13

0 Answers0