Azure Maps: Calculate and Poll a Route Matrix
See more Azure Maps Examples
Submits a two-origin, two-destination matrix to Route 2025-01-01, saves Operation-Location, polls for completion, and retrieves the result. The async workflow is useful for larger matrices; synchronous matrix requests are also available. The async limit is 50,000 origin/destination pairs.
Set resumeOperation to true to continue the operation saved in azure-maps-matrix-operation.json. The example bounds polling to 30 attempts, reports Retry-After when supplied, and keeps the saved job when it stops. Run polling in a worker or scheduler, not a UI event handler. Retrieve results promptly; the service retains them for a limited period.
It validates the service host before using credentials and rebuilds status/result URLs with an encoded string operation ID. Each matrix cell has its own status and explicit origin/destination indexes. Completion of the job does not imply that every route succeeded. Files in the current directory are replaced on subsequent runs. After an uncertain POST outcome, avoid blindly submitting duplicate work.
Uses direct Chilkat.Http calls to the Azure public-cloud endpoint. Supply a nonempty subscription_key string in private qa_data/azure/maps.json. Shared-key authentication must be enabled on the Maps account. Keep this file outside source control and public web directories, and do not embed account keys in publicly distributed applications. Microsoft Entra ID is an alternative.
Query parameters are supplied as raw text for Chilkat to encode. The code checks transport status, HTTP status, and JSON parsing separately. For throttling or temporary service failures, use bounded retries and honor Retry-After. HTTP diagnostics can contain credentials and location data; inspect them privately. Calls use verified HTTPS and do not follow redirects.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkUrlW.h>
#include <CkJsonArrayW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
CkJsonObjectW config;
config.put_Strict(true);
// Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success = config.LoadFile(L"qa_data/azure/maps.json");
if (success != true) {
wprintf(L"Could not load private Azure Maps configuration.\n");
return;
}
if (config.JsonTypeOf(L"subscription_key") != 1) {
wprintf(L"Missing or invalid subscription_key.\n");
return;
}
if (config.StringOfEquals(L"subscription_key",L"",true) == true) {
wprintf(L"A nonempty subscription_key is required.\n");
return;
}
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(30);
http.put_ReadTimeout(90);
http.put_Accept(L"application/json");
CkHttpResponseW response;
CkJsonObjectW result;
result.put_Strict(true);
CkJsonObjectW query;
// Current Azure Maps operations accept the key as a header.
http.SetRequestHeader(L"subscription-key",config.stringOf(L"subscription_key"));
// Set true to resume the saved operation instead of submitting another job.
bool resumeOperation = false;
CkJsonObjectW job;
job.put_Strict(true);
const wchar_t *operationUrl = 0;
if (resumeOperation == true) {
success = job.LoadFile(L"azure-maps-matrix-operation.json");
if (success != true) {
wprintf(L"Could not load saved matrix operation.\n");
return;
}
if (job.JsonTypeOf(L"operation_url") != 1) {
wprintf(L"Missing or invalid operation_url.\n");
return;
}
if (job.StringOfEquals(L"operation_url",L"",true) == true) {
wprintf(L"A nonempty operation_url is required.\n");
return;
}
operationUrl = job.stringOf(L"operation_url");
}
else {
CkJsonObjectW body;
body.UpdateString(L"type",L"FeatureCollection");
body.UpdateString(L"features[0].type",L"Feature");
body.UpdateString(L"features[0].geometry.type",L"MultiPoint");
body.UpdateNumber(L"features[0].geometry.coordinates[0][0]",L"-122.201399");
body.UpdateNumber(L"features[0].geometry.coordinates[0][1]",L"47.608678");
body.UpdateNumber(L"features[0].geometry.coordinates[1][0]",L"-122.136833");
body.UpdateNumber(L"features[0].geometry.coordinates[1][1]",L"47.642282");
body.UpdateString(L"features[0].properties.pointType",L"origins");
body.UpdateString(L"features[1].type",L"Feature");
body.UpdateString(L"features[1].geometry.type",L"MultiPoint");
body.UpdateNumber(L"features[1].geometry.coordinates[0][0]",L"-122.201669");
body.UpdateNumber(L"features[1].geometry.coordinates[0][1]",L"47.615076");
body.UpdateNumber(L"features[1].geometry.coordinates[1][0]",L"-122.341979");
body.UpdateNumber(L"features[1].geometry.coordinates[1][1]",L"47.609525");
body.UpdateString(L"features[1].properties.pointType",L"destinations");
body.UpdateString(L"travelMode",L"driving");
body.UpdateString(L"optimizeRoute",L"fastest");
body.UpdateString(L"traffic",L"historical");
success = http.HttpJson(L"POST",L"https://atlas.microsoft.com/route/matrix:async?api-version=2025-01-01",body,L"application/geo+json",response);
// Http methods return false for HTTP errors as well as transport failures.
if (response.get_StatusCode() == 0) {
wprintf(L"No HTTP response. Inspect diagnostics privately; they can contain credentials.\n");
return;
}
if (response.get_StatusCode() != 202) {
wprintf(L"HTTP status: %d\n",response.get_StatusCode());
wprintf(L"Error code: %s\n",response.getHeaderField(L"x-ms-error-code"));
wprintf(L"Retry-After: %s\n",response.getHeaderField(L"Retry-After"));
// Correct 400/401/403 errors before retrying. Back off for 429 and transient 5xx.
// Keep response bodies and detailed diagnostics out of public logs.
return;
}
if (success != true) {
wprintf(L"The HTTP response was incomplete.\n");
return;
}
operationUrl = response.getHeaderField(L"Operation-Location");
}
// Validate the polling destination before sending the account key to it.
CkUrlW parsed;
success = parsed.ParseUrl(operationUrl);
if (success != true) {
wprintf(L"Missing or invalid Operation-Location.\n");
return;
}
stringCompare.SetString(parsed.scheme());
bool stringMatch1 = stringCompare.ContentsEqual(L"https",true);
stringCompare.SetString(parsed.host());
bool stringMatch2 = stringCompare.ContentsEqual(L"atlas.microsoft.com",true);
stringCompare.SetString(parsed.login());
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
stringCompare.SetString(parsed.password());
bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
stringCompare.SetString(parsed.frag());
bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
if ((stringMatch1 != true) || (stringMatch2 != true) || (parsed.get_Port() != 443) || (stringMatch3 != true) || (stringMatch4 != true) || (stringMatch5 != true)) {
wprintf(L"Unexpected operation URL; refusing to send credentials.\n");
return;
}
CkStringBuilderW pathText;
pathText.Append(parsed.path());
if (pathText.StartsWith(L"/route/operations/",true) != true) {
wprintf(L"Unexpected operation path.\n");
return;
}
const wchar_t *operationId = pathText.getAfterFinal(L"/",false);
stringCompare.SetString(operationId);
bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
if (stringMatch6 == true) {
wprintf(L"Missing operation ID.\n");
return;
}
// Treat the ID as text. Rebuild URLs on the fixed Maps host.
success = http.SetUrlVar(L"operationId",operationId);
if (success != true) {
wprintf(L"Could not encode operation ID.\n");
return;
}
job.UpdateString(L"operation_url",operationUrl);
success = job.WriteFile(L"azure-maps-matrix-operation.json");
if (success != true) {
wprintf(L"Could not save the operation for resuming.\n");
return;
}
wprintf(L"Saved matrix operation. Set resumeOperation to true to resume it.\n");
if (resumeOperation != true) {
const wchar_t *submitRetryAfter = response.getHeaderField(L"Retry-After");
stringCompare.SetString(submitRetryAfter);
bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
if (stringMatch7 != true) {
wprintf(L"Resume after Retry-After: %s\n",submitRetryAfter);
return;
}
}
// Do not resubmit a POST automatically after a transport failure: the job may exist.
int attempt = 0;
bool complete = false;
while (((attempt < 30) && (complete != true))) {
// A short example limit. A production worker should schedule polling off the UI thread.
http.SleepMs(2000);
success = http.HttpNoBody(L"GET",L"https://atlas.microsoft.com/route/operations/{$operationId}?api-version=2025-01-01",response);
// Http methods return false for HTTP errors as well as transport failures.
if (response.get_StatusCode() == 0) {
wprintf(L"No HTTP response. Inspect diagnostics privately; they can contain credentials.\n");
return;
}
if (response.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",response.get_StatusCode());
wprintf(L"Error code: %s\n",response.getHeaderField(L"x-ms-error-code"));
wprintf(L"Retry-After: %s\n",response.getHeaderField(L"Retry-After"));
// Correct 400/401/403 errors before retrying. Back off for 429 and transient 5xx.
// Keep response bodies and detailed diagnostics out of public logs.
return;
}
if (success != true) {
wprintf(L"The HTTP response was incomplete.\n");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
wprintf(L"Expected a well-formed JSON response.\n");
return;
}
if (result.StringOfEquals(L"status",L"Completed",true) == true) {
complete = true;
}
else {
if (result.StringOfEquals(L"status",L"Failed",true) == true) {
wprintf(L"Matrix operation failed: %s\n",result.stringOf(L"error.code"));
return;
}
if ((result.StringOfEquals(L"status",L"Running",true) != true) && (result.StringOfEquals(L"status",L"NotStarted",true) != true)) {
wprintf(L"Unexpected operation status.\n");
return;
}
// If the service supplies Retry-After, defer to the caller's scheduler.
// Preserve the job and resume no sooner than that header permits.
const wchar_t *retryAfter = response.getHeaderField(L"Retry-After");
stringCompare.SetString(retryAfter);
bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
if (stringMatch8 != true) {
wprintf(L"Resume after Retry-After: %s\n",retryAfter);
return;
}
}
attempt = attempt + 1;
}
if (complete != true) {
wprintf(L"Polling limit reached; resume the saved operation later.\n");
return;
}
// Use the documented result endpoint on the same fixed host.
success = http.HttpNoBody(L"GET",L"https://atlas.microsoft.com/route/operations/{$operationId}/result?api-version=2025-01-01",response);
// Http methods return false for HTTP errors as well as transport failures.
if (response.get_StatusCode() == 0) {
wprintf(L"No HTTP response. Inspect diagnostics privately; they can contain credentials.\n");
return;
}
if (response.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",response.get_StatusCode());
wprintf(L"Error code: %s\n",response.getHeaderField(L"x-ms-error-code"));
wprintf(L"Retry-After: %s\n",response.getHeaderField(L"Retry-After"));
// Correct 400/401/403 errors before retrying. Back off for 429 and transient 5xx.
// Keep response bodies and detailed diagnostics out of public logs.
return;
}
if (success != true) {
wprintf(L"The HTTP response was incomplete.\n");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
wprintf(L"Expected a well-formed JSON response.\n");
return;
}
CkJsonArrayW matrix;
CkJsonObjectW cell;
success = result.ArrayOf2(L"properties.matrix",matrix);
if (success != true) {
wprintf(L"Expected a matrix array.\n");
return;
}
if (matrix.get_Size() != 4) {
wprintf(L"Expected four origin/destination results for this 2-by-2 request.\n");
return;
}
int i = 0;
while ((i < matrix.get_Size())) {
success = matrix.ObjectAt2(i,cell);
if (success != true) {
wprintf(L"Invalid matrix entry.\n");
return;
}
if (cell.JsonTypeOf(L"originIndex") != 2) {
wprintf(L"Missing or invalid originIndex.\n");
return;
}
if (cell.JsonTypeOf(L"destinationIndex") != 2) {
wprintf(L"Missing or invalid destinationIndex.\n");
return;
}
if (cell.JsonTypeOf(L"statusCode") != 2) {
wprintf(L"Missing or invalid statusCode.\n");
return;
}
// Use the explicit indexes; do not assume matrix entry order.
wprintf(L"Origin index: %d\n",cell.IntOf(L"originIndex"));
wprintf(L"Destination index: %d\n",cell.IntOf(L"destinationIndex"));
if (cell.IntOf(L"statusCode") == 200) {
if (cell.JsonTypeOf(L"distanceInMeters") != 2) {
wprintf(L"Missing or invalid distanceInMeters.\n");
return;
}
if (cell.JsonTypeOf(L"durationInSeconds") != 2) {
wprintf(L"Missing or invalid durationInSeconds.\n");
return;
}
wprintf(L"Distance (meters): %s\n",cell.stringOf(L"distanceInMeters"));
wprintf(L"Duration (seconds): %s\n",cell.stringOf(L"durationInSeconds"));
}
else {
wprintf(L"Route error: %s\n",cell.stringOf(L"error.code"));
}
i = i + 1;
}
success = result.WriteFile(L"azure-maps-matrix.json");
if (success != true) {
wprintf(L"Could not save matrix result.\n");
return;
}
wprintf(L"Saved azure-maps-matrix.json\n");
}