This is a comprehensive question about finding the shortest path in a city street network. I need to show how to:
Let me create a complete solution with multiple examples and visualizations.
I'll show you a comprehensive solution for finding shortest paths in a city street network, weighted by travel time based on speed limits.
python Copy code
import osmnx as ox
import networkx as nx
from math import radians, cos, sin, asin, sqrt
import folium
from folium import PolyLine
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
class CityRouteCalculator:
"""
Find shortest path in a city street network based on travel time.
"""
def __init__(self, city_name, network_type='drive'):
"""
Initialize with city location.
Parameters:
-----------
city_name : str
City name (e.g., "Manhattan, New York")
network_type : str
'drive', 'bike', 'walk', 'all'
"""
self.city_name = city_name
self.network_type = network_type
self.G = None
self.gdf_nodes = None
self.gdf_edges = None
def download_street_network(self):
"""Download street network from OpenStreetMap."""
print(f"Downloading street network for {self.city_name}...")
try:
# Download the graph
self.G = ox.graph_from_place(
self.city_name,
network_type=self.network_type,
simplify=True,
retain_all=False,
truncate_by_edge=True
)
# Project to UTM for accurate distance calculations (meters)
self.G = ox.project_graph(self.G, to_latlong=False)
print(f"✓ Downloaded network with {len(self.G.nodes)} nodes "
f"and {len(self.G.edges)} edges")
return self.G
except Exception as e:
print(f"Error downloading network: {e}")
return None
def add_travel_time_weights(self, default_speed=50):
"""
Add travel_time edge weights based on road speed limits.
Parameters:
-----------
default_speed : float
Default speed in km/h when speed limit not available
"""
print("Adding travel time weights to edges...")
travel_times = []
speeds = []
for u, v, key, data in self.G.edges(keys=True, data=True):
# Get speed limit or use default (in km/h)
speed = data.get('maxspeed', default_speed)
# Handle list of speeds (for divided roads)
if isinstance(speed, list):
speed = speed[0]
# Convert string to float and km/h to m/s
try:
speed = float(speed)
except (ValueError, TypeError):
speed = default_speed
# Ensure reasonable speed (between 10 and 130 km/h)
speed = max(10, min(130, speed))
speeds.append(speed)
# Get distance (in meters)
distance = data.get('length', 0)
if distance == 0:
# Calculate distance from coordinates
lat1 = self.G.nodes[u]['y']
lon1 = self.G.nodes[u]['x']
lat2 = self.G.nodes[v]['y']
lon2 = self.G.nodes[v]['x']
distance = self._haversine_distance(
lon1, lat1, lon2, lat2
) * 1000 # Convert to meters
# Calculate travel time in seconds
# time = distance (m) / speed (m/s)
speed_ms = speed / 3.6 # km/h to m/s
travel_time = distance / speed_ms if speed_ms > 0 else 0
travel_times.append(travel_time)
# Add weight attributes
self.G[u][v][key]['travel_time'] = travel_time
self.G[u][v][key]['speed'] = speed
print(f"✓ Added travel_time weights")
print(f" Speed range: {min(speeds):.1f} - {max(speeds):.1f} km/h")
print(f" Travel time range: {min(travel_times):.1f} - {max(travel_times):.1f} seconds")
return self.G
@staticmethod
def _haversine_distance(lon1, lat1, lon2, lat2):
"""
Calculate great circle distance between two points.
Returns distance in kilometers.
"""
# Convert to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers
return c * r
def find_nearest_node(self, lat, lon):
"""Find nearest node to given GPS coordinates."""
nearest_node = ox.distance.nearest_nodes(self.G, lon, lat)
return nearest_node
def calculate_shortest_path(self, start_gps, end_gps, weight='travel_time'):
"""
Calculate shortest path between two GPS coordinates.
Parameters:
-----------
start_gps : tuple
(latitude, longitude) of start point
end_gps : tuple
(latitude, longitude) of end point
weight : str
Edge weight to use: 'travel_time', 'length'
Returns:
--------
dict : Path information with route, distance, time, etc.
"""
start_lat, start_lon = start_gps
end_lat, end_lon = end_gps
# Find nearest nodes
start_node = self.find_nearest_node(start_lat, start_lon)
end_node = self.find_nearest_node(end_lat, end_lon)
print(f"\nCalculating shortest path...")
print(f"Start: ({start_lat:.4f}, {start_lon:.4f}) -> Node {start_node}")
print(f"End: ({end_lat:.4f}, {end_lon:.4f}) -> Node {end_node}")
try:
# Use Dijkstra's algorithm
route = nx.shortest_path(
self.G,
start_node,
end_node,
weight=weight
)
# Calculate path length and travel time
path_length = 0 # in meters
path_time = 0 # in seconds
speeds = []
for i in range(len(route) - 1):
u = route[i]
v = route[i + 1]
# Get the shortest edge if multiple exist
edge_data = self.G.get_edge_data(u, v)
if isinstance(edge_data, dict):
# MultiDiGraph - get the shortest edge
shortest_edge = min(
edge_data.values(),
key=lambda x: x.get('length', 0)
)
else:
shortest_edge = edge_data
path_length += shortest_edge.get('length', 0)
path_time += shortest_edge.get('travel_time', 0)
speeds.append(shortest_edge.get('speed', 0))
# Calculate route coordinates
route_coords = [(self.G.nodes[node]['y'], self.G.nodes[node]['x'])
for node in route]
result = {
'route': route,
'coordinates': route_coords,
'distance_m': path_length,
'distance_km': path_length / 1000,
'travel_time_s': path_time,
'travel_time_min': path_time / 60,
'travel_time_formatted': self._format_time(path_time),
'num_nodes': len(route),
'num_edges': len(route) - 1,
'avg_speed': np.mean(speeds) if speeds else 0,
'start_node': start_node,
'end_node': end_node
}
return result
except nx.NetworkXNoPath:
print("❌ No path found between locations")
return None
except Exception as e:
print(f"❌ Error calculating path: {e}")
return None
@staticmethod
def _format_time(seconds):
"""Format seconds into readable time string."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
if hours > 0:
return f"{hours}h {minutes}m {secs}s"
elif minutes > 0:
return f"{minutes}m {secs}s"
else:
return f"{secs}s"
def find_alternative_routes(self, start_gps, end_gps, num_routes=3,
weight='travel_time'):
"""
Find alternative routes using Yen's K-shortest paths algorithm.
Parameters:
-----------
start_gps : tuple
(latitude, longitude) of start point
end_gps : tuple
(latitude, longitude) of end point
num_routes : int
Number of alternative routes to find
weight : str
Edge weight to use
Returns:
--------
list : List of route dictionaries sorted by travel time
"""
start_lat, start_lon = start_gps
end_lat, end_lon = end_gps
start_node = self.find_nearest_node(start_lat, start_lon)
end_node = self.find_nearest_node(end_lat, end_lon)
print(f"\nFinding {num_routes} alternative routes...")
try:
# Find K shortest paths
routes = list(nx.shortest_simple_paths(
self.G,
start_node,
end_node,
weight=weight
))[:num_routes]
results = []
for i, route in enumerate(routes, 1):
# Calculate metrics for each route
path_length = 0
path_time = 0
for j in range(len(route) - 1):
u, v = route[j], route[j + 1]
edge_data = self.G.get_edge_data(u, v)
if isinstance(edge_data, dict):
shortest_edge = min(
edge_data.values(),
key=lambda x: x.get('length', 0)
)
else:
shortest_edge = edge_data
path_length += shortest_edge.get('length', 0)
path_time += shortest_edge.get('travel_time', 0)
route_coords = [(self.G.nodes[node]['y'], self.G.nodes[node]['x'])
for node in route]
results.append({
'route_num': i,
'route': route,
'coordinates': route_coords,
'distance_km': path_length / 1000,
'travel_time_min': path_time / 60,
'travel_time_formatted': self._format_time(path_time),
'num_nodes': len(route)
})
return sorted(results, key=lambda x: x['travel_time_min'])
except Exception as e:
print(f"Error finding alternative routes: {e}")
return []
def visualize_route(self, route_result, save_path='route_map.html'):
"""
Visualize route on an interactive map.
Parameters:
-----------
route_result : dict
Result from calculate_shortest_path()
save_path : str
Path to save the HTML map
"""
if not route_result:
print("No route to visualize")
return
# Get center of map
coords = route_result['coordinates']
center_lat = np.mean([coord[0] for coord in coords])
center_lon = np.mean([coord[1] for coord in coords])
# Create map
m = folium.Map(
location=[center_lat, center_lon],
zoom_start=14,
tiles='OpenStreetMap'
)
# Add route
PolyLine(
coords,
color='blue',
weight=3,
opacity=0.8,
popup=f"Route: {route_result['travel_time_formatted']}, "
f"{route_result['distance_km']:.2f} km"
).add_to(m)
# Add start marker
folium.Marker(
location=coords[0],
popup='Start',
icon=folium.Icon(color='green', icon='play')
).add_to(m)
# Add end marker
folium.Marker(
location=coords[-1],
popup='End',
icon=folium.Icon(color='red', icon='stop')
).add_to(m)
# Add some intermediate points
num_intermediate = min(5, len(coords) // 4)
for i in range(1, len(coords), len(coords) // (num_intermediate + 1)):
if i < len(coords) - 1:
folium.CircleMarker(
location=coords[i],
radius=3,
color='orange',
opacity=0.6
).add_to(m)
m.save(save_path)
print(f"✓ Map saved to {save_path}")
def visualize_multiple_routes(self, alternative_routes, save_path='alternative_routes.html'):
"""
Visualize multiple alternative routes.
Parameters:
-----------
alternative_routes : list
List of route results
save_path : str
Path to save the HTML map
"""
if not alternative_routes:
print("No routes to visualize")
return
# Get center of map from first route
coords = alternative_routes[0]['coordinates']
center_lat = np.mean([coord[0] for coord in coords])
center_lon = np.mean([coord[1] for coord in coords])
# Create map
m = folium.Map(
location=[center_lat, center_lon],
zoom_start=14,
tiles='OpenStreetMap'
)
# Color for each route
colors = ['blue', 'red', 'green', 'purple', 'orange']
for i, route in enumerate(alternative_routes):
color = colors[i % len(colors)]
PolyLine(
route['coordinates'],
color=color,
weight=2.5,
opacity=0.7,
popup=f"Route {route['route_num']}: {route['travel_time_formatted']}, "
f"{route['distance_km']:.2f} km"
).add_to(m)
# Add start and end markers
coords = alternative_routes[0]['coordinates']
folium.Marker(
location=coords[0],
popup='Start',
icon=folium.Icon(color='green', icon='play')
).add_to(m)
folium.Marker(
location=coords[-1],
popup='End',
icon=folium.Icon(color='red', icon='stop')
).add_to(m)
m.save(save_path)
print(f"✓ Map saved to {save_path}")
def plot_network_graph(self, route_result=None, figsize=(15, 12)):
"""
Plot the street network and optionally highlight the route.
Parameters:
-----------
route_result : dict, optional
Result from calculate_shortest_path() to highlight
figsize : tuple
Figure size
"""
fig, ax = plt.subplots(figsize=figsize)
# Plot the entire network
ox.plot_graph(
self.G,
ax=ax,
node_size=10,
node_color='lightgray',
edge_color='gray',
edge_linewidth=0.5,
show=False,
close=False
)
if route_result:
# Highlight the route
route = route_result['route']
edges = [(route[i], route[i+1]) for i in range(len(route)-1)]
# Get coordinates
x_coords = [self.G.nodes[node]['x'] for node in route]
y_coords = [self.G.nodes[node]['y'] for node in route]
# Plot route edges
for edge in edges:
x = [self.G.nodes[edge[0]]['x'], self.G.nodes[edge[1]]['x']]
y = [self.G.nodes[edge[0]]['y'], self.G.nodes[edge[1]]['y']]
ax.plot(x, y, 'b-', linewidth=3, alpha=0.8, zorder=10)
# Plot start and end nodes
ax.plot(x_coords[0], y_coords[0], 'go', markersize=15,
label='Start', zorder=11)
ax.plot(x_coords[-1], y_coords[-1], 'r*', markersize=20,
label='End', zorder=11)
ax.legend(loc='upper right', fontsize=12)
ax.set_title(
f"Route: {route_result['distance_km']:.2f} km, "
f"{route_result['travel_time_formatted']}",
fontsize=14,
fontweight='bold'
)
else:
ax.set_title("Street Network", fontsize=14, fontweight='bold')
plt.tight_layout()
return fig, ax
def print_route_statistics(self, route_result):
"""Print detailed route statistics."""
if not route_result:
return
print("\n" + "="*60)
print("ROUTE STATISTICS")
print("="*60)
print(f"Distance: {route_result['distance_km']:.2f} km")
print(f"Travel Time: {route_result['travel_time_formatted']}")
print(f"Average Speed: {route_result['avg_speed']:.1f} km/h")
print(f"Number of Nodes: {route_result['num_nodes']}")
print(f"Number of Edges: {route_result['num_edges']}")
print("="*60 + "\n")
def get_network_statistics(self):
"""Get statistics about the street network."""
if not self.G:
print("No network loaded")
return
print("\n" + "="*60)
print("NETWORK STATISTICS")
print("="*60)
print(f"Number of Nodes: {len(self.G.nodes)}")
print(f"Number of Edges: {len(self.G.edges)}")
print(f"Network Density: {nx.density(self.G):.4f}")
print(f"Is Connected: {nx.is_connected(self.G.to_undirected())}")
print("="*60 + "\n")
# ============================================================================
# EXAMPLE USAGE
# ============================================================================
if __name__ == "__main__":
# Initialize calculator for New York City (Manhattan)
calculator = CityRouteCalculator(
city_name="Manhattan, New York",
network_type='drive'
)
# Download street network
calculator.download_street_network()
# Get network statistics
calculator.get_network_statistics()
# Add travel time weights based on speed limits
calculator.add_travel_time_weights(default_speed=40)
# Define two locations (GPS coordinates)
# Times Square to Central Park
start = (40.7580, -73.9855) # Times Square
end = (40.7829, -73.9654) # Central Park
# Calculate shortest path
route = calculator.calculate_shortest_path(start, end, weight='travel_time')
if route:
# Print statistics
calculator.print_route_statistics(route)
# Visualize on interactive map
calculator.visualize_route(route, save_path='route_map.html')
# Plot network with highlighted route
fig, ax = calculator.plot_network_graph(route)
plt.savefig('route_plot.png', dpi=150, bbox_inches='tight')
plt.show()
# Find alternative routes
print("\n" + "="*60)
print("FINDING ALTERNATIVE ROUTES")
print("="*60)
alternative_routes = calculator.find_alternative_routes(
start, end, num_routes=3, weight='travel_time'
)
if alternative_routes:
print("\nAlternative Routes Summary:")
print("-" * 60)
for route_info in alternative_routes:
print(f"Route {route_info['route_num']}: "
f"{route_info['distance_km']:.2f} km, "
f"{route_info['travel_time_formatted']}")
# Visualize all routes
calculator.visualize_multiple_routes(alternative_routes,
save_path='alternative_routes.html')
This solution provides production-ready routing capabilities with complete analysis and visualization!