Time/Distance Matrix¶
Free
Starter
Standard
Professional
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.
Endpoint: https://api.stadiamaps.com/matrix/v1
Example Code¶
Installation Instructions
The Stadia Maps JavaScript/TypeScript SDK is available for any package manager that supports the npm registry.
npm install @stadiamaps/api
yarn add @stadiamaps/api
bun add @stadiamaps/api
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" }); (1)
// You can also use our EU endpoint to keep traffic within the EU using the basePath option:
// const config = new Configuration({ basePath: "https://api-eu.stadiamaps.com" });
// 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 });
- Learn how to get an API key in our authentication guide.
Installation Instructions
The Stadia Maps Python SDK is available through any package manager that supports PyPi.
pip install stadiamaps
poetry add stadiamaps
import os
import stadiamaps
from stadiamaps.rest import ApiException
# You can also use our EU endpoint to keep traffic within the EU like so:
# configuration = stadiamaps.Configuration(host="https://api-eu.stadiamaps.com")
configuration = stadiamaps.Configuration()
# Configure API key authentication (ex: via environment variable). (1)
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)
try:
location_a = {"lat": 40.042072, "lon": -76.306572}
location_b = {"lat": 39.992115, "lon": -76.781559}
location_c = {"lat": 39.984519, "lon": -76.6956}
req = stadiamaps.MatrixRequest(
id="matrix",
sources=[
stadiamaps.MatrixWaypoint.from_dict(location_a),
],
targets=[
stadiamaps.MatrixWaypoint.from_dict(location_b),
stadiamaps.MatrixWaypoint.from_dict(location_c),
],
costing=stadiamaps.MatrixCostingModel.PEDESTRIAN,
)
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)
- Learn how to get an API key in our authentication guide.
Installation Instructions
If aren't already using Maven Central, add the repository in your Gradle build script.
repositories {
mavenCentral()
}
Then, add the API package and its dependencies.
dependencies {
val retrofitVersion = "2.11.0"
// API package
implementation("com.stadiamaps:api:3.2.1")
// Dependencies
implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
implementation("com.squareup.moshi:moshi-adapters:1.14.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.10.0")
implementation("com.squareup.retrofit2:retrofit:$retrofitVersion")
implementation("com.squareup.retrofit2:converter-moshi:$retrofitVersion")
implementation("com.squareup.retrofit2:converter-scalars:$retrofitVersion")
}
dependencies {
def retrofitVersion = "2.11.0"
// API package
implementation 'com.stadiamaps:api:3.2.1'
// Dependencies
implementation 'com.squareup.moshi:moshi-kotlin:1.15.1'
implementation 'com.squareup.moshi:moshi-adapters:1.15.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'
implementation "com.squareup.retrofit2:retrofit:${retrofitVersion}"
implementation "com.squareup.retrofit2:converter-moshi:${retrofitVersion}"
implementation "com.squareup.retrofit2:converter-scalars:${retrofitVersion}"
}
Our API package is available on Maven Central.
All you need to do is add a few dependencies to your pom.xml
.
<properties>
<retrofit.version>2.9.0</retrofit.version>
</properties>
<dependencies>
<!-- API package -->
<dependency>
<groupId>com.stadiamaps</groupId>
<artifactId>api</artifactId>
<version>3.2.1</version>
</dependency>
<!-- Dependencies -->
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-kotlin</artifactId>
<version>1.15.1</version>
</dependency>
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-adapters</artifactId>
<version>1.15.1</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-moshi</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-scalars</artifactId>
<version>${retrofit.version}</version>
</dependency>
</dependencies>
// 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) (1)
val apiKey = System.getenv("STADIA_API_KEY") ?: throw RuntimeException("API Key not set")
// Defining the host is optional and defaults to https://api.stadiamaps.com
// You can also use our EU endpoint to keep traffic within the EU like so:
// val client = ApiClient(baseUrl = "https://api-eu.stadiamaps.com")
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(RoutingApi::class.java)
// Set up the request.
// Note: this code is blocking for demonstration purposes.
// If you're using Kotlin with coroutines,
// you can also use these asynchronously within suspend functions.
// Synchronous code can enqueue a callback to avoid blocking
// (you'll definitely want to do one of these instead when on the main thread of an app).
// See the docs for details: https://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html
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 = MatrixCostingModel.auto,
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()}")
}
- Learn how to get an API key in our authentication guide.
Installation Instructions
Our Swift SDK is distributed using the Swift Package Manager (SPM).
Apple's documentation
shows how to add a Swift Package dependency to your Xcode project.
On the Add Package screen, you can find our package by its repository URL: https://github.com/stadiamaps/stadiamaps-api-swift
.
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 (1)
StadiaMapsAPI.customHeaders = ["Authorization": "Stadia-Auth YOUR-API-KEY"]
// Optionally use our EU endpoint to keep traffic within the EU
// StadiaMapsAPI.basePath = "https://api-eu.stadiamaps.com"
}
// 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: https://developer.apple.com/documentation/swift/task.
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...
print(res)
}
- Learn how to get an API key in our authentication guide.
Installation Instructions
Composer
To install the package via Composer,
add stadiamaps/stadiamaps-api-php
to your composer.json
:
{
"require": {
"stadiamaps/stadiamaps-api-php": "1.*"
}
}
Then run composer install
.
Manual Installation
You can also download the files manually and include autoload.php
in your scripts:
<?php
require_once('/path/to/OpenAPIClient-php/vendor/autoload.php');
<?php
// use or require, depending on your installation method.
// Configure API key authorization (replace with your Stadia Maps API key) (1)
$config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR-API-KEY');
// You can also use our EU endpoint to keep traffic within the EU using setHost:
// $config = Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR-API-KEY')->setHost('https://api-eu.stadiamaps.com');
$apiInstance = new OpenAPI\Client\Api\RoutingApi(
new GuzzleHttp\Client(),
$config
);
try {
$req = (new MatrixRequest())
->setId('matrix')
->setSources([
(new MatrixWaypoint())->setLat(58.891957)->setLon(22.726262),
(new MatrixWaypoint())->setLat(59.1558)->setLon(23.762758),
])
->setTargets([
(new MatrixWaypoint())->setLat(59.176153)->setLon(23.846605),
(new MatrixWaypoint())->setLat(59.562853)->setLon(23.096114),
])
->setCosting(CostingModel::BICYCLE);
$result = $apiInstance->timeDistanceMatrix($req);
} catch (Exception $e) {
// Add your error handling here
echo 'Exception when calling the Stadia Maps API: ', $e->getMessage(), PHP_EOL;
}
- Learn how to get an API key in our authentication guide.
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"
}' "https://api.stadiamaps.com/matrix/v1?api_key=YOUR-API-KEY"
Service Limits¶
We limit time/distance matrix complexity on two dimensions: the number of matrix elements and the straight-line distance between all locations.
Matrix elements are a simple multiplication of the dimensions of the input. For example, a request with 3 sources (origins) and 5 targets (destinations) has 3 x 5 = 15 elements. The size limits depend on your plan.
Costing/mode of travel | Max elements (Standard) | Max elements (Professional) | Max b-line distance between all locations |
---|---|---|---|
Automobile, bus, truck, and taxi | 625 | 10,000 | 400 kilometers |
All others | 625 | 10,000 | 200 kilometers |
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).