๐Ÿ—บ๏ธ OSMnx Route Analysis Cheat Sheet

๐Ÿ“ฆ 1. Installation & Setup

# Install required libraries
!pip install osmnx==1.9.1 folium -q

# Import essentials
import osmnx as ox
import networkx as nx
import folium
import pandas as pd
import matplotlib.pyplot as plt

# Configure OSMnx
ox.settings.use_cache = True
  

๐ŸŒ 2. Fetch Map Data

# Define location
place = "Chatuchak, Bangkok, Thailand"

# Get street network graph
G = ox.graph_from_place(place, network_type='drive')

# Quick visualization
ox.plot_graph(G, node_size=0, edge_linewidth=0.5)
  

๐Ÿ“Š 3. Explore Network Data

# Convert to GeoDataFrames
edges, nodes = ox.graph_to_gdfs(G)

# Explore edge attributes
edges[['highway', 'length', 'name']].head()

# Road type distribution
edges['highway'].value_counts().plot(kind='bar')
  

๐Ÿ“ 4. Set Origin & Destination

# Define coordinates (lat, lon)
origin = (13.7563, 100.5018)      # Example: Bangkok
destination = (13.7942, 100.5423)  # Example: Chatuchak

# Find nearest nodes
orig_node = ox.nearest_nodes(G, origin[1], origin[0])
dest_node = ox.nearest_nodes(G, destination[1], destination[0])
  

๐Ÿ›ค๏ธ 5. Find Shortest Path (Distance)

# Calculate shortest path by distance
route = nx.astar_path(G, orig_node, dest_node, weight='length')

# Get total distance
distance = nx.path_weight(G, route, weight='length')
print(f"Distance: {distance:.0f} meters")
  

๐Ÿ—บ๏ธ 6. Visualize Route on Map

# Create interactive map with route
route_map = ox.plot_route_folium(
    G, route,
    route_map=None,
    route_color='blue',
    route_opacity=0.8
)

# Add markers
folium.Marker(origin, popup="Start", icon=folium.Icon(color='green')).add_to(route_map)
folium.Marker(destination, popup="End", icon=folium.Icon(color='red')).add_to(route_map)

# Display map
route_map
  

๐Ÿ“ˆ 7. Analyze Route

# Convert route to GeoDataFrame
route_gdf = ox.utils_graph.route_to_gdf(G, route)

# Analyze route segments
print(f"Number of segments: {len(route_gdf)}")
print(f"Streets used: {route_gdf['name'].dropna().unique()}")
print(f"Road types: {route_gdf['highway'].value_counts().to_dict()}")
  

๐Ÿ”„ 8. Compare Alternative Routes

# New destination
alt_destination = (13.8000, 100.5500)
alt_dest_node    = ox.nearest_nodes(G, alt_destination[1], alt_destination[0])

# Calculate alternative route
alt_route     = nx.astar_path(G, orig_node, alt_dest_node, weight='length')
alt_distance  = nx.path_weight(G, alt_route, weight='length')

# Compare distances
print(f"Original: {distance:.0f}m | Alternative: {alt_distance:.0f}m")
  

โฑ๏ธ 9. Add Travel Time Weights

# Define speeds by road type (km/h)
speeds = {
    'motorway': 80,
    'trunk': 60,
    'primary': 50,
    'secondary': 40,
    'tertiary': 30,
    'residential': 25,
    'unclassified': 20
}

# Convert to m/s and apply to graph
speed_mps = {k: v * 1000 / 3600 for k, v in speeds.items()}
G = ox.add_edge_speeds(G, speed_mps)
G = ox.add_edge_travel_times(G)
  

โšก 10. Find Fastest Route (Time)

# Calculate fastest route by time
fast_route = nx.astar_path(G, orig_node, dest_node, weight='travel_time')

# Get travel time
travel_time = nx.path_weight(G, fast_route, weight='travel_time')
print(f"Travel time: {travel_time/60:.1f} minutes")

# Compare with shortest distance route
if fast_route != route:
    print("โš ๏ธ Fastest route differs from shortest route!")
  

๐Ÿ’ก Quick Tips

๐Ÿ”ง Common Issues & Solutions

# If location not found
try:
    G = ox.graph_from_place(place)
except:
    # Try with larger area or coordinates
    G = ox.graph_from_point((lat, lon), dist=1000)

# If no path found
try:
    route = nx.astar_path(G, orig, dest)
except nx.NetworkXNoPath:
    print("No path exists between these points!")
  

๐Ÿ“š Useful Functions Reference

Function Purpose
ox.graph_from_place() Get network by place name
ox.graph_from_point() Get network around a point
ox.nearest_nodes() Find nearest node to coordinates
ox.plot_route_folium() Plot route on interactive map
nx.astar_path() Find optimal path (A* algorithm)
nx.path_weight() Calculate total weight of path