'Plotting a route with osmnx

I'm trying to develop a code to plot a route in a map with osnmx. This is what I have:

route=[292257954, 429200554, 1187086228, 1179868692, 430284828]
fig, ax = ox.plot.plot_graph_route(G_map, route, route_color='r', route_linewidth=4, route_alpha=0.5, orig_dest_size=100, ax=None)

In the route list, I have the nodes written as IDs of OSM. But i get this error:

    fig, ax = ox.plot.plot_graph_route(G_map, route, route_color='r', route_linewidth=4, route_alpha=0.5, orig_dest_size=100, ax=None)

  File ~\anaconda3\envs\ox\lib\site-packages\osmnx\plot.py:303 in plot_graph_route
    data = min(G.get_edge_data(u, v).values(), key=lambda d: d["length"])

AttributeError: 'NoneType' object has no attribute 'values'

Could anyone help me?



Solution 1:[1]

  • have reconstructed graph by looking up OSMID in overpass
  • clearly this is not a valid route, also one of the nodes does not exist after reconstructing graph
[
  "No path between 292257954 and 429200554.",
  "No path between 429200554 and 1187086228.",
  "Either source 1187086228 or target 1179868692 is not in G",
  "Either source 1179868692 or target 430284828 is not in G"
]

full code

import requests
import pandas as pd
import shapely
import osmnx as ox
import networkx as nx
import json

route = [292257954, 429200554, 1187086228, 1179868692, 430284828]

# get lat/lon of osmids
df = pd.DataFrame(
    requests.get(
        f"http://overpass-api.de/api/interpreter?data=[out:json]; node(id:{','.join([str(n) for n in route])});out;"
    ).json()["elements"]
)

# get graph bound by nodes in list
poly = shapely.geometry.MultiPoint(df.loc[:, ["lon", "lat"]].values).convex_hull
G_map = ox.graph_from_polygon(poly, network_type="drive")

rr = []
err = []
for a,b in zip(route, route[1:]):
    try:
        r = nx.shortest_path(G_map, a, b, weight='length')
        rr.append(r)
    except nx.NetworkXNoPath as e:
        err.append(str(e))
    except nx.NodeNotFound as e:
        err.append(str(e))

print(json.dumps(err, indent=2))
        
if len(rr)>0:
    fig, ax = ox.plot.plot_graph_route(
        G_map,
        rr,
        route_color="r",
        route_linewidth=4,
        route_alpha=0.5,
        orig_dest_size=100,
        ax=None,
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Raymond