Directions and Distance Matrix - MCP Integration
Directions and Distance Matrix - MCP Integration
What They Do
Directions API: Calculates routes between two or more points with turn-by-turn directions, distance, and travel time. Supports driving, walking, bicycling, and transit modes.
Distance Matrix API: Calculates travel distance and time between multiple origins and multiple destinations simultaneously. Perfect for routing optimization and travel time analysis.
Both available via MCP tools - just call the function!
Music Use Case: Tour and Soundwalk Planning
Calculate route between venues:
python# Using MCP tool route = maps_directions( origin="Tijuana Jazz Club, Tijuana", destination="Black Box, Tijuana", mode="walking" ) print(f"Distance: {route['routes'][0]['legs'][0]['distance']['text']}") # "450 meters" print(f"Duration: {route['routes'][0]['legs'][0]['duration']['text']}") # "6 mins" # Turn-by-turn steps for step in route['routes'][0]['legs'][0]['steps']: print(step['html_instructions']) # "Head east on Av. Revolución" # "Turn right onto Calle 7"
Multi-venue tour routing:
python# Calculate route with waypoints tour_route = maps_directions( origin="Tijuana Jazz Club", destination="El Pasaje Estudio", waypoints="Black Box|ENTONO Live Music", # Pipe-separated mode="driving" ) total_time = sum(leg['duration']['value'] for leg in tour_route['routes'][0]['legs']) print(f"Total tour time: {total_time / 60} minutes")
Soundwalk feasibility analysis:
python# Check walk times between recording points points = [ "Tijuana Jazz Club, Tijuana", "Foro Nebraska, Tijuana", "La Bohème, Tijuana", "Black Box, Tijuana" ] # Calculate walk time from each point to next for i in range(len(points) - 1): route = maps_directions( origin=points[i], destination=points[i+1], mode="walking" ) duration = route['routes'][0]['legs'][0]['duration']['text'] distance = route['routes'][0]['legs'][0]['distance']['text'] print(f"{points[i]} → {points[i+1]}") print(f" Walk: {duration} ({distance})\n") # Result: Determine if soundwalk route is realistic (<10 min between points)
Travel time matrix for venue selection:
python# From which venue can we reach all studios fastest? venues = ["Tijuana Jazz Club", "ENTONO Live Music"] studios = ["El Pasaje Estudio", "Master Q Estudios", "BlindFold Records"] matrix = maps_distance_matrix( origins=venues, destinations=studios, mode="driving" ) # Returns travel time from each venue to each studio # Rows = origins (venues), Columns = destinations (studios) for i, origin in enumerate(matrix['origin_addresses']): print(f"\nFrom {origin}:") for j, dest in enumerate(matrix['destination_addresses']): element = matrix['results'][i]['elements'][j] print(f" → {dest}: {element['duration']['text']}") # Example output: # From Tijuana Jazz Club: # → El Pasaje Estudio: 3 mins # → Master Q Estudios: 18 mins # → BlindFold Records: 25 mins
Environmental Research Use Case: Inspection Routing and Response Planning
Facility-to-downtown travel times:
python# How long to get from treatment plants to downtown? (emergency response) plants = [ "WWTP La Morita, Tijuana", "San Antonio de los Buenos Wastewater Treatment Plant, Tijuana" ] destinations = [ "Downtown Tijuana", "Tijuana City Hall" ] matrix = maps_distance_matrix( origins=plants, destinations=destinations, mode="driving" ) # Real results from earlier exploration: # WWTP La Morita → Downtown: 29 mins (23.9 km) # San Antonio de los Buenos → Downtown: 33 mins (13.4 km)
Monitoring site inspection route:
python# Plan daily inspection route through monitoring sites sites = [ "32.4552,-116.8605", # WWTP La Morita "32.4698,-117.0828", # San Antonio de los Buenos "32.4569,-116.9080" # CESPT Plant ] route = maps_directions( origin=sites[0], destination=sites[-1], waypoints="|".join(sites[1:-1]), mode="driving" ) total_distance = sum(leg['distance']['value'] for leg in route['routes'][0]['legs']) total_time = sum(leg['duration']['value'] for leg in route['routes'][0]['legs']) print(f"Total inspection route: {total_distance/1000:.1f} km in {total_time/60:.0f} minutes") # Export directions for field crew for i, leg in enumerate(route['routes'][0]['legs']): print(f"\n{'Leg '+str(i+1)+': '+leg['start_address']+ ' → '+leg['end_address']}") for step in leg['steps']: print(f" {step['html_instructions']} ({step['distance']['text']})")
Optimal crew dispatching:
python# Which crew is closest to emergency site? crew_locations = [ "32.5100,-117.0200", # Crew A (north sector) "32.4800,-116.9500", # Crew B (central sector) "32.4500,-116.8800" # Crew C (east sector) ] emergency_site = "32.4650,-116.9300" # Reported overflow matrix = maps_distance_matrix( origins=crew_locations, destinations=[emergency_site], mode="driving" ) # Find fastest response time response_times = [ matrix['results'][i]['elements'][0]['duration']['value'] for i in range(len(crew_locations)) ] fastest_crew = response_times.index(min(response_times)) print(f"Dispatch Crew {chr(65+fastest_crew)}: {min(response_times)/60:.0f} minute ETA")
MCP Tools Available
1. maps_directions
Calculate route with turn-by-turn directions.
Parameters:
origin- Starting point (address or "lat,lng")destination- Ending point (address or "lat,lng")mode- Travel mode: "driving", "walking", "bicycling", "transit"waypoints(optional) - Intermediate stops (pipe-separated: "stop1|stop2")
Returns:
routesarray with:legs- Segments between waypointsdistance- {text: "5.2 km", value: 5200}duration- {text: "12 mins", value: 720}steps- Turn-by-turn instructionsstart_address,end_address
Example:
pythonroute = maps_directions( origin="Tijuana Jazz Club", destination="El Pasaje Estudio", mode="walking" ) leg = route['routes'][0]['legs'][0] print(f"Walk {leg['distance']['text']} in {leg['duration']['text']}") print("\nDirections:") for step in leg['steps']: print(f"- {step['html_instructions']} ({step['distance']['text']})")
2. maps_distance_matrix
Calculate travel times between multiple origins and destinations.
Parameters:
origins- Array of starting pointsdestinations- Array of ending pointsmode- Travel mode: "driving", "walking", "bicycling", "transit"
Returns:
origin_addresses- Formatted addresses for originsdestination_addresses- Formatted addresses for destinationsresults- Matrix of travel timesresults[i]['elements'][j]- Travel from origin[i] to dest[j]distance- {text, value}duration- {text, value}status- "OK" or error code
Example:
pythonmatrix = maps_distance_matrix( origins=["Tijuana Jazz Club", "Black Box"], destinations=["El Pasaje Estudio", "Master Q Estudios"], mode="driving" ) # Create travel time table for i, origin in enumerate(matrix['origin_addresses']): for j, dest in enumerate(matrix['destination_addresses']): element = matrix['results'][i]['elements'][j] if element['status'] == 'OK': print(f"{origin} → {dest}: {element['duration']['text']}")
How They Work
Directions API:
- Calculates optimal route using road network data
- Considers traffic (if premium tier), road restrictions, turn prohibitions
- Returns polyline (encoded path) for map rendering
- Mode affects route: walking uses sidewalks/paths, driving uses roads
Distance Matrix API:
- Parallel calculation of multiple origin-destination pairs
- More efficient than calling Directions API repeatedly
- Returns only summary (distance/time), no turn-by-turn steps
- Useful for optimization algorithms (find nearest facility, etc.)
MCP tools:
- Handle API authentication automatically
- Parse responses into convenient structures
- Built-in error handling
- Perfect for scripting and automation
When to Use Them
Music/Audio projects:
- Tour planning (venue-to-venue routes)
- Soundwalk design (ensure walking distances realistic)
- Multi-city tour optimization
- Equipment transport logistics
Environmental research:
- Inspection route planning
- Emergency response time analysis
- Crew dispatch optimization
- Facility accessibility assessment
Use Directions API when:
- Need turn-by-turn directions
- Rendering route on map (polyline included)
- Single route calculation
- User navigation required
Use Distance Matrix API when:
- Comparing multiple routes simultaneously
- Optimization problems (nearest facility, shortest total route)
- Only need distance/time, not directions
- Batch processing (more efficient than repeated Directions calls)
Don't use for:
- Very long routes (>10 waypoints = slow, consider Route Optimization API)
- Real-time traffic updates (use Maps SDK with live traffic layer)
- Public transit schedules (use Transit API for detailed schedules)
Pro Tips
Optimize waypoint order:
python# Add optimize:true to automatically reorder waypoints for shortest route route = maps_directions( origin="Tijuana Jazz Club", destination="El Pasaje Estudio", waypoints="optimize:true|Black Box|ENTONO|Foro Nebraska", mode="driving" ) # Check optimized order waypoint_order = route['routes'][0]['waypoint_order'] print(f"Optimal order: {waypoint_order}") # e.g., [1, 0, 2] = reordered
Alternative routes:
python# Request multiple route options route = maps_directions( origin="WWTP La Morita", destination="Downtown Tijuana", alternatives="true", mode="driving" ) print(f"Found {len(route['routes'])} alternative routes") for i, r in enumerate(route['routes']): leg = r['legs'][0] print(f"Route {i+1}: {leg['distance']['text']} in {leg['duration']['text']}")
Departure time for traffic:
pythonimport time # Calculate travel time at specific time (traffic-aware, premium tier only) tomorrow_9am = int(time.time()) + 86400 # Unix timestamp route = maps_directions( origin="Tijuana Jazz Club", destination="Estadio Caliente", mode="driving", departure_time=tomorrow_9am ) # Returns duration_in_traffic (with traffic) vs duration (without)
Avoid tolls/highways:
pythonroute = maps_directions( origin="Tijuana", destination="Rosarito", mode="driving", avoid="tolls|highways" )
Distance Matrix for nearest facility:
pythondef find_nearest_facility(user_location, facilities): matrix = maps_distance_matrix( origins=[user_location], destinations=facilities, mode="driving" ) # Find shortest duration durations = [ matrix['results'][0]['elements'][i]['duration']['value'] for i in range(len(facilities)) ] nearest_index = durations.index(min(durations)) return facilities[nearest_index], durations[nearest_index] / 60 # Example nearest, travel_time = find_nearest_facility( user_location="32.5200,-117.0300", facilities=["WWTP La Morita", "San Antonio de los Buenos", "CESPT Plant"] ) print(f"Nearest facility: {nearest} ({travel_time:.0f} minutes away)")
Real-World Example: Water Quality Sampling Route Optimizer
Problem: Visit 10 monitoring sites across Tijuana watershed. What's the shortest route?
Solution:
python# Monitoring sites (in no particular order) sites = [ "32.5679,-117.1241", # Estuary mouth "32.5450,-117.0850", # Río Alamar confluence "32.5200,-117.0300", # Urban runoff point "32.4850,-116.9500", # Mid-watershed "32.4650,-116.9300", # Industrial zone "32.4552,-116.8605", # WWTP La Morita outfall "32.4698,-117.0828", # San Antonio plant "32.4569,-116.9080", # CESPT plant "32.4400,-116.8800", # Agricultural runoff "32.5100,-116.9200" # Residential area ] # Start and end at lab lab = "32.5300,-117.0200" # Calculate optimal route route = maps_directions( origin=lab, destination=lab, waypoints="optimize:true|" + "|".join(sites), mode="driving" ) # Print optimized route print("Optimized sampling route:") waypoint_order = route['routes'][0]['waypoint_order'] for i, wp_index in enumerate(waypoint_order): print(f"{i+1}. Site {wp_index+1}: {sites[wp_index]}") # Calculate total time legs = route['routes'][0]['legs'] total_time = sum(leg['duration']['value'] for leg in legs) total_distance = sum(leg['distance']['value'] for leg in legs) print(f"\nTotal route: {total_distance/1000:.1f} km in {total_time/60:.0f} minutes") print("Add ~15 minutes per site for sampling = " + f"{total_time/60 + len(sites)*15:.0f} minutes total")
Related APIs
- Places API - Find destinations for routing
- Geocoding API - Convert addresses to coordinates for routing
- Elevation API - Add elevation profile to routes
- Route Optimization API - Advanced multi-stop optimization
- Maps JavaScript API - Render routes on interactive maps
Resources
- Directions API Documentation
- Distance Matrix API Documentation
- MCP Google Maps Server
- Travel mode comparison and best practices