Distance Matrix
Contents
Introduction
When optimizing driver routes or deciding where to locate facilities, transportation and logistics companies often need to calculate distances and travel times between thousands of locations.
The Distance Matrix API allows you to submit a large matrix of origin and destination locations and generate travel times and distances for each origin-destination pair. These large requests are processed asynchronously and the results are retrieved as a series of pages. The API can process up to a 5,000 * 5,000 matrix per request.
The API only supports origins and destinations that are submitted as latitude and longitude pairs. To convert large numbers of addresses to coordinates, please refer to our Single Search Batch Geocoding API.
Getting Started
To gain access to the Distance Matrix API, you must be a Premium Web Services subscriber with an add-on Distance Matrix license. Please contact your Trimble Maps representative or our Sales team for more information.
Workflow
The Distance Matrix API requires three steps:
- Authenticate your Trimble Maps API key and receive a JSON Web Token (JWT). All subsequent requests must pass the JWT in the request header.
- Submit a POST request with your origins and destinations. There are optional route options to customize the routes that are used to calculate times and distances, such as a truck route versus an auto route. (The most simple example of this is that a truck route will often differ in distance from an auto route, which has more roads available because of its smaller size.) This request will process asynchronously and the results can be retrieved by the GET request specified in the step below.
- Submit a series of GET requests to retrieve the pages of your results with travel times and distances. Depending on the number of origins and destinations, it can take some time to build the routes and calculate travel time/distances. We recommended polling the service every few seconds for results.
Authentication
Resource URL
https://api.trimblemaps.com/identity/v2/token
POST /identity/v2/token
Authenticate your request to the server by using the API key provided by Trimble Maps. If the authentication is successful, the server creates and sends a JSON Web Token (JWT) in the response. To access the API resources, all subsequent requests must pass the JWT in the request header.
Request Body
| Name | Description | Data Type |
|---|---|---|
apiKey
| API key provided by Trimble Maps |
string |
Sample JSON Post Body
{
"apikey": "string"
}
Response
| Name | Description | Data Type |
|---|---|---|
token
| Auth token that expires after a set time interval |
string |
tokenType
| Token Type to be included in Authorization header
|
string |
expires
| The date and time at which the token is set to expire |
DateTime |
Sample Response
{
"token": "string",
"tokenType": "string",
"expires": "2022-02-15T19:18:23.228Z"
}
POST Distance Matrix
Resource URL
https://api.trimblemaps.com/routing/v1/matrix
POST /routing/v1/matrix
Submit a request to create a distance matrix by passing in:
- A list of origins and destinations as latitude and longitude
Coordsobjects. - A worldwide data
Regionfor your request. - (Optionally) an
Optionsobject to customize the routes that are used to calculate times and distances. If you do not pass in this object, the routes will be created using default settings, including the default truck dimensions.
Request Body
Authorization: bearer {token}
| Name | Description | Data Type | Required |
|---|---|---|---|
Origins
| An array of Coords object that represents the origins.
|
object | Y |
Destinations
| An array of Coords object that represents the destinations.
|
object | Y |
Region
| The data region in which stop coordinates lie. - NA, EU, AF, AS, ME, SA, OC |
string | Y for regions outside of the default region, North America - NA
|
Options
| Route options that influence the distance and time. You can pass as many options as you would like to customize the route. A schema for the Options object is below. Full definitions for all of the parameters are available here.
|
object | No |
Options JSON Schema
"options": {
"estimatedTimeOptions": {
"etaetd": 0,
"dateOption": 0,
"dateAndTime": {
"calendarDate": "string",
"dayOfWeek": 0,
"timeOfDay": "string",
"timeZone": 0
}
},
"useTraffic": true,
"truckStyle": 0,
"afSetIDs": [
0
],
"afSetNames": [
"string"
],
"bordersOpen": true,
"classOverrides": 0,
"customRoadSpeeds": [
{
"roadCategory": 1,
"speed": 0
}
],
"distanceUnits": 0,
"elevLimit": 0,
"ferryDiscourage": true,
"fuelConsumption": 0,
"fuelRoute": true,
"fuelType": 0,
"governorSpeedLimit": 0,
"hazMatType": 0,
"highwayOnly": true,
"hubRouting": true,
"maintainHeading": true,
"overrideRestrict": true,
"refrigerated": true,
"routeOptimization": 0,
"routingType": 0,
"sideOfStreetAdherence": 0,
"tollDiscourage": true,
"trailerCfg": {
"typeOfTrailer": 1,
"count": 0,
"maxHeight": "string",
"maxWeight": 0,
"maxAxles": 0,
"engine": {
"hybrid": true,
"emissionType": 2,
"minPollutionVeh": true
}
},
"truckCfg": {
"units": 0,
"height": "string",
"length": "string",
"width": "string",
"weight": "string",
"axles": 0,
"lcv": true,
"maxWeightPerAxleGroup": 0,
"tireCount": 0
},
"tunnelCategory": 0,
"useSites": true,
"vehicleProfile": 0,
"vehicleType": 0,
"avoidCountry": [
"string"
],
"avoidState": [
"string"
],
"favorCountry": [
"string"
],
"favorState": [
"string"
],
"includeTrimblePlaceIDs": true,
"tollRoads": 1,
"hazMatTypes": [
0
],
"tunnelCategories": [
0
],
"useCrossStreetTurnAvoidance": true,
"restrictionZones": {
"congestionZone": 0,
"lowEmissionZone": 0,
"ultraLowEmissionZone": 0
},
"profileName": "string"
},
"region": "string"
}
Sample JSON Post Body
{
"Origins": [
{
"Coords": {
"Lon": "13.3833",
"Lat": "52.5167"
}
},
{
"Coords": {
"Lon": "10.0000",
"Lat": "53.5500"
}
}
],
"Destinations": [
{
"Coords": {
"Lon": "8.2667",
"Lat": "50.0000"
}
},
{
"Coords": {
"Lon": "10.6864",
"Lat": "53.8697"
}
}
],
"Region": "EU",
"Options": {
"vehicleType": 0,
"estimatedTimeOptions": {
"eTAETD": 1,
"dateOption": 1,
"dateAndTime": {
"calendarDate": "11/21/2021",
"dayOfWeek": 0,
"timeOfDay": "6:00 AM",
"timeZone": 0
}
}
}
}
Response
| Name | Description | Data Type |
|---|---|---|
requestid
| A GUID request id that represents the submitted POST distance matrix request. This value is used to retrieve results using the GET API. |
GUID |
Sample Response
{
"requestid": "87123d07-4782-4h08-beae-555680dcbc65"
}
GET Distance Matrix Results
Resource URL
https://api.trimblemaps.com/routing/v1/matrix/{request-id}?next_page={next-page}
GET /routing/v1/matrix/{request-id}
Retrieve the results of the Distance Matrix by passing the requestid returned by the POST request. The results include travel distances and times for each pair of origins and destinations. Each pair is identified by an originIndex and a destinationIndex, and the index number is based on the order the origins and destinations were submitted, starting at 0. (The origin and destination pairs may be returned out of order depending on calculation time.)
The results are limited to 500 a page. The response also includes the next_page parameter, which is used in subsequent GET requests to retrieve the next page of results.
- A
nullin thenext_pageindicates all results are retrieved. - A response with
next_page = 0and emptyresultsindicates that the request is still in process and no results are available yet.
Request Parameters
Authorization: bearer {token}
| Name | Description | Data Type | Required |
|---|---|---|---|
requestId
| The distance matrix requestId returned by the POST request. |
GUID | Y |
next_page
| An index into next page of results for the submitted request. Default: 0
|
int | Y, for all pages after the default first page. |
Response
| Name | Description | Data Type |
|---|---|---|
requestId
| The submitted distance matrix requestId
|
GUID |
next_page
| An index into next page of results. A value of 0 indicates no results are available yet, whereas a value of null indicates final page of the results.
|
int |
originIndex
| Zero-based index that indicates the origin location and can be used to match with the origin in the submitted request. |
int |
destinationIndex
| Zero-based index that indicates the destination location and can be used to match up to the destination in the submitted request. |
int |
distance
| The route distance between the origin and destination. Default values are in miles. (Set "DistanceUnits": 1 in your POST request Options object to return distances in kilometers.)
|
double |
time
| The total time taken by the route between the origin and destination. The time will be in hh:mm:ss.
|
string |
errors
| Any errors with geocoding the coordinates or calculation of the route between the origin and destination. |
string |
Sample Response
{
"requestid": "87123d07-4782-4h08-beae-555680dcbc65",
"next_page": 1,
"results": [
{
"originIndex": 0,
"destinationIndex": 0,
"distance": 100.55,
"time": "07:32:42",
"errors": ""
},
{
"originIndex": 0,
"destinationIndex": 1,
"distance": 202.31,
"time": "03:59:09",
"errors": ""
}
]
}
Python Sample Code
"""
Sample of how to use Distance Matrix
1. Authenticate with API key
2. POST an Async request
3. Retrieve/store the results
"""
import requests
import time
import json
input_file = "data.json"
output_file = "results.json"
api_key = "API KEY HERE"
# 1. Authenticate with API key
auth_data = {
"apikey": api_key
}
AUTHENTICATE_URL: str = "https://api.trimblemaps.com/identity/v2/token"
response = requests.post(AUTHENTICATE_URL, json=auth_data)
response = response.json()
try:
auth_token: str = response["token"]
headers = {"Authorization": "Bearer "+ auth_token}
print("Successfully retrieved JWT token", flush=True)
except (KeyError, TypeError):
print("JWT token could not be generated")
auth_token = ""
# 2. POST an Async request
ASYNC_REQUEST_URL: str = "https://api.trimblemaps.com/routing/v1/matrix"
with open(input_file) as json_file:
body = json.load(json_file)
response = requests.post(ASYNC_REQUEST_URL, json=body, headers=headers)
request_id: str = response.json()["requestid"]
next_page: int = 0
total_count: int = 0
timer: int = 1
res: list[dict] = []
count = 0
time_start = time.perf_counter()
while next_page != None:
URL: str = "{}/{}?next_page={}".format(ASYNC_REQUEST_URL, request_id, next_page)
response: requests.Response = requests.get(URL, headers=headers)
res_json: dict = response.json()
next_page = res_json["next_page"]
res.extend(res_json["results"])
if next_page != 0:
count = count + 1
if count%10 == 0:
print("Retrieved " + str(count) + " pages", flush=True)
# Wait before requesting again (capped at 4 seconds)
time.sleep(timer)
if (timer == 4):
pass
else:
timer *= 2
time_end = time.perf_counter()
# 3. Retrieve/store the results
with open(output_file, 'w') as fp:
print("Results written to " + output_file, flush=True)
json.dump(res, fp)
print(f"Time taken: {time_end - time_start:0.4f} seconds")
Python Sample Code - Large Requests
Requests for matrices larger than 5000 * 5000.
"""
Sample of how to use the Distance Matrix API for big matrices.
This is used when matrices are too big for one call.
NOTE:
A thread is allocated for each divided matrix
1. Authenticate with API key
2. Divide up the input into smaller matrices that can be processed
3. POST an Async requests (threaded for performance)
4. Retrieve/store the results
"""
from datetime import datetime
import requests
import time
import json
import numpy as np
import threading
class MatrixScript:
class Case:
def __init__(self, id: str, progress: bool, headers: dict):
"""
:param id: request id
:param progress: whether the user wants to see how many pages have been processed
:param headers: auth information
"""
self.id: str = id
self.progress: bool = progress
self.headers: dict = headers
self.res: list = []
def run(self) -> None:
"""
Runs an individual case by the request id
"""
ASYNC_REQUEST_URL: str = "https://api.trimblemaps.com/routing/v1/matrix"
time_start = datetime.now()
next_page: int = 0
prev_page: int = 0
page_count: int = 0
first_fetch: bool = True
wait: bool = True
print("Starting request: {}".format(self.id))
while next_page != None:
# Waiting to get results
if first_fetch:
time.sleep(3 * 60)
first_fetch = False
else:
if wait:
time.sleep(4)
URL: str = "{}/{}?next_page={}".format(ASYNC_REQUEST_URL, self.id, next_page)
results = requests.get(URL, headers=self.headers)
next_page = results.json()["next_page"]
if next_page == prev_page:
wait = True
# More results to be fetched
else:
wait = False
prev_page = next_page
page_count += 1
# Add to results
self.res.extend(results.json()["results"])
if self.progress:
print("Thread id: {}, request id: {}, curr page count: {}, curr res length: {}".format(threading.get_native_id(), self.id, page_count, len(self.res)))
time_end = datetime.now()
print("Time taken for request id ({}): {}".format(self.id, time_end - time_start))
def __init__(self, key: str, file_name: str, output_name: str, size: int = 5000) -> None:
"""
Initialize variables that are needed to call async service
API_KEY: str - key that has service enabled
size: int - max size for inputs (cannot exceed 5000 bc max size is 5000 x 5000)
filename: name of input file
output: name of file to be saved to
request_ids: all of the request ids once requested
"""
self.API_KEY: str = key
self.size: int = size
self.filename: str = file_name
self.output: str = output_name
self.input_matrix_origins: list[dict] = []
self.input_matrix_destinations: list[dict] = []
self.request_ids: list[str] = []
self.options: dict = {}
# Where the output is stored
self.res: list[dict] = []
# Authenticating
auth_data: dict = {
"apikey": self.API_KEY
}
AUTHENTICATE_URL: str = "https://api.trimblemaps.com/identity/v2/token"
response = requests.post(AUTHENTICATE_URL, json=auth_data)
response = response.json()
try:
auth_token: str = response["token"]
headers: dict = {"Authorization": "Bearer "+ auth_token}
except (KeyError, TypeError):
print("Auth token could not be generated")
headers: dict = {}
self.headers: dict = headers
def divide_input(self) -> None:
"""
Divides the input into smaller sizes to match
"""
# 2. Divide up input
with open(self.filename) as json_file:
body: dict = json.load(json_file)
# To be added to all of the requests
self.options: dict = body["Options"]
# Divide
self.input_matrix_origins = self.split_given_size(body["Origins"], self.size)
self.input_matrix_destinations = self.split_given_size(body["Destinations"], self.size)
def run_all(self, see_progress: bool = True) -> None:
"""
Runs multi threaded script
:param see_progress: Print out progress checks (default -> True)
"""
# 3. POST Async requests
ASYNC_REQUEST_URL: str = "https://api.trimblemaps.com/routing/v1/matrix"
time_start = datetime.now()
for ori in self.input_matrix_origins:
for des in self.input_matrix_destinations:
# Matrix request
req = {
"Options": self.options,
"Origins": list(ori),
"Destinations": list(des)
}
res = requests.post(ASYNC_REQUEST_URL, headers=self.headers, json=req)
id: str = res.json()["requestid"]
self.request_ids.append(id)
threads: list[threading.Thread] = []
cases: list[MatrixScript.Case] = []
for request_id in self.request_ids:
cases.append(MatrixScript.Case(request_id, see_progress, self.headers))
threads.append(threading.Thread(target=cases[-1].run))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
time_end = datetime.now()
# Add up the result
for case in cases:
self.res.extend(case.res)
# 4. Retrieve/store the results
with open(self.output, "w") as f:
json.dump(self.res, f)
print("Completed calculations and retrieved + stored successfully")
print("Time taken: {}".format(time_end - time_start))
# Helpers
def split_given_size(self, a: list, size: int) -> list:
"""
Divides input into appropriate size with leftovers
:param a: array to be split
:param size: the size that is desired
:returns: array that is split
"""
return np.split(a, np.arange(size,len(a),size))
def main() -> None:
# Input API key
key: str = input("API key: ")
# Get a valid size
while True:
size: int = int(input("Preferred processing size (enter 0 if none): "))
if size >= 0 and size <= 5000:
if size == 0:
size = 5000
break
print("Size must be between 0 and 5000 (inclusive)...")
# Retrieve filenames
filename: str = input("Filename of json to process (ex: file.json): ")
output_name: str = input("Filename to output results to (ex: response.json): ")
# Create matrix script
processor: MatrixScript = MatrixScript(key, filename, output_name, size)
processor.divide_input()
processor.run_all()
if __name__ == "__main__":
main()