Skip to content

Time/Distance Matrix





The time/distance matrix API lets you compare travel times between a set of possible start and end points. You can use it to find travel time between one location and multiple others (ex: a hotel or apartment and nearby points of interest), or specify multiple starting and ending points (these are called sources and targets) at once.

For rich vehicle routing problem (VRP) optimizations across a fleet of vehicles, our time/distance matrix API can be used as input to a number of solvers, including VROOM and OptaPlanner.


Example Code


Get started quickly with code samples using our official SDKs or cURL. Official SDKs include documentation of all request and response models, either as separate pages, or through docstrings and autocomplete in most IDEs. If you are building for another language or want to try out requests in a browser, refer to our interactive API reference.

import { RoutingApi, Configuration, MatrixRequest } from '@stadiamaps/api';

// If you are writing for a backend application or can't use domain-based auth,
// then you'll need to add your API key like so:
// const config = new Configuration({ apiKey: "YOUR-API-KEY" });
// You can also use our EU endpoint to keep traffic within the EU using the basePath option:
// const config = new Configuration({ basePath: "" });
// const api = new RoutingApi(config);
const api = new RoutingApi();

const req: MatrixRequest = {
    id: "matrix",
    sources: [
            lat: 40.744014,
            lon: -73.990508
    targets: [
            lat: 40.744014,
            lon: -73.990508
            lat: 40.739735,
            lon: -73.979713
            lat: 40.752522,
            lon: -73.985015
            lat: 40.750117,
            lon: -73.983704
            lat: 40.750552,
            lon: -73.993519
    costing: "pedestrian"
const res = await api.timeDistanceMatrix({ matrixRequest: req });
import os
import stadiamaps
from import ApiException

# You can also use our EU endpoint to keep traffic within the EU like so:
# configuration = stadiamaps.Configuration(host="")
configuration = stadiamaps.Configuration()

# Configure API key authentication (ex: via environment variable).
configuration.api_key['ApiKeyAuth'] = os.environ["API_KEY"]

with stadiamaps.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = stadiamaps.RoutingApi(api_client)

        location_a = {"lat": 40.042072, "lon": -76.306572}
        location_b = {"lat": 39.992115, "lon": -76.781559}
        req = stadiamaps.MatrixRequest(

        res = api_instance.time_distance_matrix(req)
    except ApiException as e:
        # Add your error handling here
        print("Exception when calling the Stadia Maps API: %s\n" % e)
// Imports (at the top of your source file; we've used some wildcard imports for simplicity)
import com.stadiamaps.api.apis.*
import com.stadiamaps.api.auth.ApiKeyAuth
import com.stadiamaps.api.infrastructure.*
import com.stadiamaps.api.models.*

// Set your API key (from an environment variable in this case)
val apiKey = System.getenv("STADIA_API_KEY") ?: throw RuntimeException("API Key not set")

// Defining the host is optional and defaults to
// You can also use our EU endpoint to keep traffic within the EU like so:
// val client = ApiClient(baseUrl = "")
val client = ApiClient()
client.addAuthorization("ApiKeyAuth", ApiKeyAuth("query", "api_key", apiKey))

// Configure a service for the group of APIs we want to talk to
val service = client.createService(

// Set up the request. Note: if you're using Kotlin with coroutines, you can also await
// rather than executing synchronously when using suspend functions.
val locationA = MatrixWaypoint(40.042072, -76.306572)
val locationB = MatrixWaypoint(39.992115, -76.781559)
val locationC = MatrixWaypoint(39.984519, -76.6956)
val costingOptions = CostingOptions(auto = AutoCostingOptions(useHighways = 0.3))  // Take the scenic route ;)

val req = MatrixRequest(
    id = "matrix",
    sources = listOf(locationA),
    targets = listOf(locationB, locationC),
    costing =,
    costingOptions = costingOptions,
val res = service.timeDistanceMatrix(req).execute()

if (res.isSuccessful) {
    println("Found result: ${res.body()}")
} else {
    println("Request failed with error code ${res.code()}")
import StadiaMaps

// This setup code can go anywhere before you actually make an API call (typically in your app init)
func setupStadiaMapsAPI() {
    // Set your API key
    StadiaMapsAPI.customHeaders = ["Authorization": "Stadia-Auth YOUR-API-KEY"]
    // Optionally use our EU endpoint to keep traffic within the EU
    // StadiaMapsAPI.basePath = ""

// This function demonstrates how to call the Stadia Maps API.
// If you have not yet adopted async/await in your Swift codebase, you can use the Task API
// to call async functions in a non-async context:
func myFunction() async throws {
    let req = MatrixRequest(id: "matrix",
                            sources: [
                                MatrixWaypoint(lat: 40.042072, lon: -76.306572),
                            targets: [
                                MatrixWaypoint(lat: 39.984519, lon: -76.6956),
                                MatrixWaypoint(lat: 39.992115, lon: -76.781559),
                            costing: .auto,
                            costingOptions: CostingOptions(auto: AutoCostingOptions(useTolls: 0.3)))  // Take the scenic route :)
    let res = try await RoutingAPI.timeDistanceMatrix(matrixRequest: req)

    // Do something with the response...
curl -X POST -H "Content-Type: application/json" -d '{
    "id": "matrix",
    "sources": [
            "lat": 40.744014,
            "lon": -73.990508
    "targets": [
            "lat": 40.744014,
            "lon": -73.990508
            "lat": 40.739735,
            "lon": -73.979713
            "lat": 40.752522,
            "lon": -73.985015
            "lat": 40.750117,
            "lon": -73.983704
            "lat": 40.750552,
            "lon": -73.993519
    "costing": "pedestrian"
}' ""

Complementary APIs

The time/distance matrix inputs are geographic coordinates. If you have human-readable addresses, you can use our forward geocoding and structured geocoding APIs to convert to latitude and longitude.

For certain applications, the optimized routing API may also be useful to calculate an optimized route for a single vehicle (Traveling Salesman Problem).

Next Steps