Distance Matrix API
Distance Matrix API allows you to get information about travel time and distance between points on the map.
Using Distance Matrix API, you can find points with the required time to reach and use this information to implement your own algorithms for solving routing problems.
Distance Matrix API supports two modes of operation:
- Calculating requests that contain up to 25 starting or ending points in synchronous mode. In this mode, the request returns the result of calculation.
- Calculating requests that contain up to 1000 starting or ending points in asynchronous mode. In this mode, the request returns the task ID, which should be used to periodically check if the calculation is complete (see Large number of points).
Distance Matrix API returns only brief information about the route (distance and travel time). To get the full geometry of a route, use Directions API.
Move your mouse over a marker on the map to find out the distance and driving time to it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2GIS Distance matrix API</title>
<meta name="description" content="Several destination points example" />
<style>
html,
body,
#container {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#tooltip {
padding: 12px 16px;
background: #fff;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
border-radius: 4px;
display: none;
position: fixed;
pointer-events: none;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="tooltip"></div>
<script src="https://mapgl.2gis.com/api/js/v1"></script>
<script>
const reqUrl = `https://routing.api.2gis.com/get_dist_matrix?key=Your directions API access key&version=2.0`;
const map = new mapgl.Map('container', {
center: [37.668598, 55.76259],
zoom: 10,
key: 'Your API access key',
});
function renderMarkersWithData(routes) {
function generateTooltipText(index) {
const data = routes.find((item) => item.target_id === index);
if (!data) return undefined;
return `distance: ${data.distance.toLocaleString()} m.<br>by car: ${Math.round(
data.duration / 60,
)} min.`;
}
const tooltipEl = document.getElementById('tooltip');
const startPoint = points.shift();
const marker = new mapgl.Marker(map, {
coordinates: [startPoint.lon, startPoint.lat],
label: {
text: 'Point of departure',
fontSize: 13,
},
});
points.forEach((point, index) => {
const marker = new mapgl.Marker(map, {
coordinates: [point.lon, point.lat],
icon: 'https://docs.2gis.com/img/dotMarker.svg',
});
marker.on('mouseover', (event) => {
// Offset in pixels
const offset = 5;
tooltipEl.style.top = `${event.point[1] + offset}px`;
tooltipEl.style.left = `${event.point[0] + offset}px`;
tooltipEl.innerHTML = generateTooltipText(index + 1);
tooltipEl.style.display = 'block';
});
marker.on('mouseout', (e) => {
tooltipEl.style.display = 'none';
});
});
}
const points = [
{
lat: 55.716226,
lon: 37.729171,
},
{
lat: 55.723976,
lon: 37.624403,
},
{
lat: 55.71893,
lon: 37.564967,
},
{
lat: 55.730375,
lon: 37.483024,
},
];
fetch(reqUrl, {
method: 'POST',
body: JSON.stringify({
points,
sources: [0],
targets: [1, 2, 3],
mode: 'driving',
start_time: new Date().toISOString(),
}),
})
.then((res) => res.json())
.then((parsed) => renderMarkersWithData(parsed.routes))
.catch((err) => console.error('error', err));
</script>
</body>
</html>
Getting an access key
Usage of this API requires an API key. To obtain the key, fill out the form at dev.2gis.com/order.
Request example
To get the information about a route, send a POST request to the /get_dist_matrix
endpoint. Specify your API key as the key
parameter in the query string. Additionally, specify the required API version as the version
parameter (2.0
by default).
https://routing.api.2gis.com/get_dist_matrix?key=API_KEY&version=2.0
Coordinates for the route and other parameters must be sent as a JSON string in the request body.
You can specify several starting and end points in the request body. For each specified starting point, a route will be built to each specified end point.
For example, to build routes for two starting points and two end points, send the following request:
curl --request POST \
--url 'https://routing.api.2gis.com/get_dist_matrix?key=API_KEY&version=2.0' \
--header 'Content-Type: application/json' \
--data '{
"points": [
{
"lat": 54.99770587584445,
"lon": 82.79502868652345
},
{
"lat": 54.99928130973027,
"lon": 82.92137145996095
},
{
"lat": 55.04533538802211,
"lon": 82.98179626464844
},
{
"lat": 55.072470687600536,
"lon": 83.04634094238281
}
],
"sources": [0, 1],
"targets": [2, 3]
}'
The points
parameter is an array of route points. The sources
and targets
parameters are arrays of indices that determine which points of the points
array are starting and end points, respectively.
Caution!
If the number of points in either
sources
ortargets
array exceeds 25, the request will return an error. To get route information with a large number of points, use the asynchronous method.
Response example
For each pair of starting and ending points, the request will return route information including the route length in meters (distance
) and travel time in seconds (duration
). The point indices will be specified in the source_id
and target_id
fields. If a route could not be built for a particular pair of points, the status
field will contain the string "FAIL".
More detailed information about response fields can be found in API Reference.
{
"generation_time": 3349,
"routes": [
{
"distance": 11287,
"duration": 1319,
"source_id": 0,
"status": "OK",
"target_id": 2
},
{
"distance": 3839,
"duration": 603,
"source_id": 0,
"status": "OK",
"target_id": 3
},
{
"distance": 12245,
"duration": 1094,
"source_id": 1,
"status": "OK",
"target_id": 2
},
{
"distance": 11418,
"duration": 931,
"source_id": 0,
"status": "OK",
"target_id": 3
}
]
}
Route types
Shortest route in time
By default, the server returns the shortest car route in time using current traffic data. To build a specific type of route, set the type
parameter in the request.
{
"points": [...],
"type": "jam" // car route using current traffic data
}
Instead of current traffic data, you can build a route using statistical traffic data. To do this, specify the statistics
route type and the required date and time in RFC 3339 format as the start_time
parameter.
{
"points": [...],
"type": "statistics", // car route using statistical traffic data...
"start_time": "2020-05-15T15:52:01Z" // ...as of 15 May 2020, 15:52:01 UTC
}
Shortest route in distance
To build the shortest route in distance, even if it is not optimal due to traffic jams, specify the shortest
route type.
{
"points": [...],
"type": "shortest" // car route ignoring traffic
}
Public transport lanes
You can also include public transport lanes when building a car route, which can be useful for taxi and bus routes. To do this, add the mode
parameter with the value taxi
.
{
"points": [...],
"mode": "taxi", // car route including public transport lanes...
"type": "shortest" // ...and ignoring traffic
}
Pedestrian route
To build a pedestrian route, use the mode
parameter with the value walking
.
{
"points": [...],
"mode": "walking" // pedestrian route
}
Bicycle route
To build a bicycle route, use the mode
parameter with the value bicycle
.
{
"points": [...],
"mode": "bicycle" // bicycle route
}
Avoiding road types
When building a route, you can exclude certain types of roads, such as toll roads or dirt roads, using the filters
parameter, and exclude specific areas using the exclude
parameter. For more information on using these parameters, see the corresponding sections of Directions API.
Response format
By default, responses are in the JSON format. To get a response in the Protocol Buffers format, specify the response_format=protobuf
parameter in the query string:
https://routing.api.2gis.com/get_dist_matrix?key=API_KEY&version=2.0&response_format=protobuf
A schema of the protobuf format is available at DistanceMatrix.proto.
Large number of points
⚠ This functionality is currently in beta. To learn more about terms of use, email us at api@2gis.com
When using a large number of starting or ending points (more than 25), you need to use the asynchronous approach:
- Create a route building task.
- Periodically check the status of the task until the route calculation is complete.
- Get the calculated route when the task is complete.
Creating a route building task
To create a task, you need to send a POST request to the /async_matrix/create_task/get_dist_matrix
. Specify your API key as the key
parameter in the query string. Additionally, specify the required API version as the version
parameter (2.0
by default).
https://routing.api.2gis.com/async_matrix/create_task/get_dist_matrix?key=API_KEY&version=2.0
Coordinates for the route and other parameters must be sent as a JSON string in the request body.
For example, to build routes for two starting points and two end points, send the following request:
curl --request POST \
--url 'https://routing.api.2gis.com/async_matrix/create_task/get_dist_matrix?key=API_KEY&version=2.0' \
--header 'Content-Type: application/json' \
--data '{
"points": [
{
"lat": 54.99770587584445,
"lon": 82.79502868652345
},
{
"lat": 54.99928130973027,
"lon": 82.92137145996095
},
{
"lat": 55.04533538802211,
"lon": 82.98179626464844
},
{
"lat": 55.072470687600536,
"lon": 83.04634094238281
}
],
"sources": [0, 1],
"targets": [2, 3]
}'
The request will return information about the created task, including the task identifier (task_id
), which should be used to check the task status.
{
"task_id": "TASK_ID",
"status ": "TASK_CREATED"
}
Check task status
To check the status of the task, send a GET request to the /async_matrix/result/get_dist_matrix/{task_id}?key=API_KEY
endpoint, where task_id
is the identifier of the created task.
curl --request GET \
--url 'http://routing.api.2gis.com/async_matrix/result/get_dist_matrix/TASK_ID?key=API_KEY' \
--header 'accept: application/json'
The request will return the current status of the task and a link to the solution file if the task has been completed successfully. The structure of the solution file is identical to the structure of a response to a synchronous request.
{
// Task identifier.
"task_id": "TASK_ID",
// Task status.
"status": "TASK_DONE",
// Status code.
"code": 200,
// Additional information about the task status.
"message": "start_time_ms=16516816106601123 calc_time_ms=14419 attract_time=4 build_time=28 points_count=3 source_count=1 target_count=2",
// Link to the solution file.
"result_link": "http://storage_host:port/dm/TASK_ID.response.json"
}
Tasks can have the following statuses:
TASK_CREATED
- task has been created.TASK_IN_QUEUE
- task is in a queue, waiting to be processed.TASK_IN_PROGRESS
- task is being processed.TASK_DONE
- task was completed.TASK_CANCELED
- task was cancelled (see themessage
field for more details).