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 CkJava Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
CkStringBuilder stringCompare = new CkStringBuilder();
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
CkJsonObject config = new CkJsonObject();
config.put_Strict(true);
// Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success = config.LoadFile("qa_data/azure/maps.json");
if (success != true) {
System.out.println("Could not load private Azure Maps configuration.");
return;
}
if (config.JsonTypeOf("subscription_key") != 1) {
System.out.println("Missing or invalid subscription_key.");
return;
}
if (config.StringOfEquals("subscription_key","",true) == true) {
System.out.println("A nonempty subscription_key is required.");
return;
}
CkHttp http = new CkHttp();
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(30);
http.put_ReadTimeout(90);
http.put_Accept("application/json");
CkHttpResponse response = new CkHttpResponse();
CkJsonObject result = new CkJsonObject();
result.put_Strict(true);
CkJsonObject query = new CkJsonObject();
// Current Azure Maps operations accept the key as a header.
http.SetRequestHeader("subscription-key",config.stringOf("subscription_key"));
// Set true to resume the saved operation instead of submitting another job.
boolean resumeOperation = false;
CkJsonObject job = new CkJsonObject();
job.put_Strict(true);
String operationUrl;
if (resumeOperation == true) {
success = job.LoadFile("azure-maps-matrix-operation.json");
if (success != true) {
System.out.println("Could not load saved matrix operation.");
return;
}
if (job.JsonTypeOf("operation_url") != 1) {
System.out.println("Missing or invalid operation_url.");
return;
}
if (job.StringOfEquals("operation_url","",true) == true) {
System.out.println("A nonempty operation_url is required.");
return;
}
operationUrl = job.stringOf("operation_url");
}
else {
CkJsonObject body = new CkJsonObject();
body.UpdateString("type","FeatureCollection");
body.UpdateString("features[0].type","Feature");
body.UpdateString("features[0].geometry.type","MultiPoint");
body.UpdateNumber("features[0].geometry.coordinates[0][0]","-122.201399");
body.UpdateNumber("features[0].geometry.coordinates[0][1]","47.608678");
body.UpdateNumber("features[0].geometry.coordinates[1][0]","-122.136833");
body.UpdateNumber("features[0].geometry.coordinates[1][1]","47.642282");
body.UpdateString("features[0].properties.pointType","origins");
body.UpdateString("features[1].type","Feature");
body.UpdateString("features[1].geometry.type","MultiPoint");
body.UpdateNumber("features[1].geometry.coordinates[0][0]","-122.201669");
body.UpdateNumber("features[1].geometry.coordinates[0][1]","47.615076");
body.UpdateNumber("features[1].geometry.coordinates[1][0]","-122.341979");
body.UpdateNumber("features[1].geometry.coordinates[1][1]","47.609525");
body.UpdateString("features[1].properties.pointType","destinations");
body.UpdateString("travelMode","driving");
body.UpdateString("optimizeRoute","fastest");
body.UpdateString("traffic","historical");
success = http.HttpJson("POST","https://atlas.microsoft.com/route/matrix:async?api-version=2025-01-01",body,"application/geo+json",response);
// Http methods return false for HTTP errors as well as transport failures.
if (response.get_StatusCode() == 0) {
System.out.println("No HTTP response. Inspect diagnostics privately; they can contain credentials.");
return;
}
if (response.get_StatusCode() != 202) {
System.out.println("HTTP status: " + response.get_StatusCode());
System.out.println("Error code: " + response.getHeaderField("x-ms-error-code"));
System.out.println("Retry-After: " + response.getHeaderField("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) {
System.out.println("The HTTP response was incomplete.");
return;
}
operationUrl = response.getHeaderField("Operation-Location");
}
// Validate the polling destination before sending the account key to it.
CkUrl parsed = new CkUrl();
success = parsed.ParseUrl(operationUrl);
if (success != true) {
System.out.println("Missing or invalid Operation-Location.");
return;
}
stringCompare.SetString(parsed.scheme());
boolean stringMatch1 = stringCompare.ContentsEqual("https",true);
stringCompare.SetString(parsed.host());
boolean stringMatch2 = stringCompare.ContentsEqual("atlas.microsoft.com",true);
stringCompare.SetString(parsed.login());
boolean stringMatch3 = stringCompare.ContentsEqual("",true);
stringCompare.SetString(parsed.password());
boolean stringMatch4 = stringCompare.ContentsEqual("",true);
stringCompare.SetString(parsed.frag());
boolean stringMatch5 = stringCompare.ContentsEqual("",true);
if ((stringMatch1 != true) || (stringMatch2 != true) || (parsed.get_Port() != 443) || (stringMatch3 != true) || (stringMatch4 != true) || (stringMatch5 != true)) {
System.out.println("Unexpected operation URL; refusing to send credentials.");
return;
}
CkStringBuilder pathText = new CkStringBuilder();
pathText.Append(parsed.path());
if (pathText.StartsWith("/route/operations/",true) != true) {
System.out.println("Unexpected operation path.");
return;
}
String operationId = pathText.getAfterFinal("/",false);
stringCompare.SetString(operationId);
boolean stringMatch6 = stringCompare.ContentsEqual("",true);
if (stringMatch6 == true) {
System.out.println("Missing operation ID.");
return;
}
// Treat the ID as text. Rebuild URLs on the fixed Maps host.
success = http.SetUrlVar("operationId",operationId);
if (success != true) {
System.out.println("Could not encode operation ID.");
return;
}
job.UpdateString("operation_url",operationUrl);
success = job.WriteFile("azure-maps-matrix-operation.json");
if (success != true) {
System.out.println("Could not save the operation for resuming.");
return;
}
System.out.println("Saved matrix operation. Set resumeOperation to true to resume it.");
if (resumeOperation != true) {
String submitRetryAfter = response.getHeaderField("Retry-After");
stringCompare.SetString(submitRetryAfter);
boolean stringMatch7 = stringCompare.ContentsEqual("",true);
if (stringMatch7 != true) {
System.out.println("Resume after Retry-After: " + submitRetryAfter);
return;
}
}
// Do not resubmit a POST automatically after a transport failure: the job may exist.
int attempt = 0;
boolean 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("GET","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) {
System.out.println("No HTTP response. Inspect diagnostics privately; they can contain credentials.");
return;
}
if (response.get_StatusCode() != 200) {
System.out.println("HTTP status: " + response.get_StatusCode());
System.out.println("Error code: " + response.getHeaderField("x-ms-error-code"));
System.out.println("Retry-After: " + response.getHeaderField("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) {
System.out.println("The HTTP response was incomplete.");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
System.out.println("Expected a well-formed JSON response.");
return;
}
if (result.StringOfEquals("status","Completed",true) == true) {
complete = true;
}
else {
if (result.StringOfEquals("status","Failed",true) == true) {
System.out.println("Matrix operation failed: " + result.stringOf("error.code"));
return;
}
if ((result.StringOfEquals("status","Running",true) != true) && (result.StringOfEquals("status","NotStarted",true) != true)) {
System.out.println("Unexpected operation status.");
return;
}
// If the service supplies Retry-After, defer to the caller's scheduler.
// Preserve the job and resume no sooner than that header permits.
String retryAfter = response.getHeaderField("Retry-After");
stringCompare.SetString(retryAfter);
boolean stringMatch8 = stringCompare.ContentsEqual("",true);
if (stringMatch8 != true) {
System.out.println("Resume after Retry-After: " + retryAfter);
return;
}
}
attempt = attempt+1;
}
if (complete != true) {
System.out.println("Polling limit reached; resume the saved operation later.");
return;
}
// Use the documented result endpoint on the same fixed host.
success = http.HttpNoBody("GET","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) {
System.out.println("No HTTP response. Inspect diagnostics privately; they can contain credentials.");
return;
}
if (response.get_StatusCode() != 200) {
System.out.println("HTTP status: " + response.get_StatusCode());
System.out.println("Error code: " + response.getHeaderField("x-ms-error-code"));
System.out.println("Retry-After: " + response.getHeaderField("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) {
System.out.println("The HTTP response was incomplete.");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
System.out.println("Expected a well-formed JSON response.");
return;
}
CkJsonArray matrix = new CkJsonArray();
CkJsonObject cell = new CkJsonObject();
success = result.ArrayOf2("properties.matrix",matrix);
if (success != true) {
System.out.println("Expected a matrix array.");
return;
}
if (matrix.get_Size() != 4) {
System.out.println("Expected four origin/destination results for this 2-by-2 request.");
return;
}
int i = 0;
while ((i < matrix.get_Size())) {
success = matrix.ObjectAt2(i,cell);
if (success != true) {
System.out.println("Invalid matrix entry.");
return;
}
if (cell.JsonTypeOf("originIndex") != 2) {
System.out.println("Missing or invalid originIndex.");
return;
}
if (cell.JsonTypeOf("destinationIndex") != 2) {
System.out.println("Missing or invalid destinationIndex.");
return;
}
if (cell.JsonTypeOf("statusCode") != 2) {
System.out.println("Missing or invalid statusCode.");
return;
}
// Use the explicit indexes; do not assume matrix entry order.
System.out.println("Origin index: " + cell.IntOf("originIndex"));
System.out.println("Destination index: " + cell.IntOf("destinationIndex"));
if (cell.IntOf("statusCode") == 200) {
if (cell.JsonTypeOf("distanceInMeters") != 2) {
System.out.println("Missing or invalid distanceInMeters.");
return;
}
if (cell.JsonTypeOf("durationInSeconds") != 2) {
System.out.println("Missing or invalid durationInSeconds.");
return;
}
System.out.println("Distance (meters): " + cell.stringOf("distanceInMeters"));
System.out.println("Duration (seconds): " + cell.stringOf("durationInSeconds"));
}
else {
System.out.println("Route error: " + cell.stringOf("error.code"));
}
i = i+1;
}
success = result.WriteFile("azure-maps-matrix.json");
if (success != true) {
System.out.println("Could not save matrix result.");
return;
}
System.out.println("Saved azure-maps-matrix.json");
}
}