A quick example of obtaining the code, using it effectively, and applying it to your workflow
Sign up at distancematrix.ai to obtain an API key. This key will grant you access to both our Distance Matrix and Geocoding APIs.
# Example: Assign your API key to a variable in your code export
export DISTANCE_MATRIX_API_KEY="YOUR_API_KEY"
Use the Geocoding API to transform passenger and driver addresses into latitude/longitude coordinates—essential for precise routing and ETA calculations.
import os
import requests
api_key = os.environ.get("DISTANCE_MATRIX_API_KEY")
geocode_url = "https://api.distancematrix.ai/maps/api/geocode/json"
def geocode_address(address):
params = {
'address': address,
'key': api_key
}
response = requests.get(geocode_url, params=params).json()
location = response['results'][0]['geometry']['location']
return location['lat'], location['lng']
# Example: Convert a passenger's address into coordinates
passenger_lat, passenger_lng = geocode_address("1600 Amphitheatre Parkway, Mountain View, CA")
Once you have coordinates, use the Distance Matrix API to find travel times and distances. The API factors in real-time traffic and other conditions for accurate results.
distance_url = "https://api.distancematrix.ai/maps/api/distancematrix/json"
def get_time_distance(origins, destinations):
# origins and destinations should be lists of "lat,lng" strings
params = {
'origins': '|'.join(origins),
'destinations': '|'.join(destinations),
'key': api_key
}
response = requests.get(distance_url, params=params).json()
return response
# Example: Check travel times between multiple drivers and one passenger
driver_coords = [
"37.422,-122.084", # Driver 1
"37.7749,-122.4194" # Driver 2
]
passenger_coord = [f"{passenger_lat},{passenger_lng}"]
matrix_data = get_time_distance(driver_coords, passenger_coord)
The Distance Matrix API provides durations and distances for each origin-destination pair. By running a comparison locally, you can identify the driver who can arrive the fastest and estimate the ETA. While this isn’t a built-in feature of the API itself, it’s straightforward to implement using the matrix data.
Display ETAs in your customer app, use coordinates to show live driver positions on a map, and feed distance/duration data into your fare calculation logic. The APIs are flexible and easy to integrate into your existing systems.