Question

Why are nodes not found in a graph in OSMNX when the graph is all of New York and the nodes were found from coordinates within that city?

Here is my code:

import osmnx as ox

# Use the following commands to download the graph file of NYC
G = ox.graph_from_place('New York City', network_type='drive', simplify=True)

# Coordinates for origin and destination
orig_x = 40.6662
orig_y = -73.9340
dest_x = 40.6576
dest_y = -73.9208

# Find the nearest nodes
orig_node = ox.distance.nearest_nodes(G, orig_x, orig_y, return_dist=True)
dest_node = ox.distance.nearest_nodes(G, dest_x, dest_y, return_dist=True)
print(f"Origin node: {orig_node}, Destination node: {dest_node}")

# Calculate the shortest path
route = ox.shortest_path(G, orig_node, dest_node, weight='length')
travel_secs = sum(G[u][v][0]['length'] for u, v in zip(route[:-1], route[1:])) * 186.411821
print(f"Travel time (seconds): {travel_secs}")

I'm trying to find the shortest path between these two points but I get

networkx.exception.NodeNotFound: Either source 15056632.490169104 or target 15056625.267485507 is not in G

Sorry if this is something obvious, I'm new to this library and haven't found any good documentation on this issue.

 2  28  2
1 Jan 1970

Solution

 1

That's because of two problems : You swapped the x/y (i.e, New York is at -73.935242/40.730610) and considered the osmid/dist as pair of coordinates when asking for the shortest_path :

import osmnx as ox

G = ox.graph_from_place("New York City", network_type="drive", simplify=True)

orig_x, orig_y = -73.9340, 40.6662
dest_x, dest_y = -73.9208, 40.6576

orig_node = ox.distance.nearest_nodes(G, orig_x, orig_y)
dest_node = ox.distance.nearest_nodes(G, dest_x, dest_y)

route = ox.shortest_path(G, orig_node, dest_node, "length")
travel_secs = nx.path_weight(G, route, "length") * 186.411821

# or if route is not needed
# nx.shortest_path_length(G, orig_node, dest_node, "length") * 186.411821

print(f"Travel time (seconds): {travel_secs}")  # 314517.75262762

enter image description here

2024-07-22
Timeless