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 Delphi ActiveX Downloads
var
success: Integer;
stringCompare: TChilkatStringBuilder;
config: TChilkatJsonObject;
http: TChilkatHttp;
response: TChilkatHttpResponse;
result: TChilkatJsonObject;
query: TChilkatJsonObject;
resumeOperation: Integer;
job: TChilkatJsonObject;
operationUrl: WideString;
body: TChilkatJsonObject;
parsed: TChilkatUrl;
stringMatch1: Integer;
stringMatch2: Integer;
stringMatch3: Integer;
stringMatch4: Integer;
stringMatch5: Integer;
pathText: TChilkatStringBuilder;
operationId: WideString;
stringMatch6: Integer;
submitRetryAfter: WideString;
stringMatch7: Integer;
attempt: Integer;
complete: Integer;
retryAfter: WideString;
stringMatch8: Integer;
matrix: TChilkatJsonArray;
cell: TChilkatJsonObject;
i: Integer;
begin
success := 0;
stringCompare := TChilkatStringBuilder.Create(Self);
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
config := TChilkatJsonObject.Create(Self);
config.Strict := 1;
// Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success := config.LoadFile('qa_data/azure/maps.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not load private Azure Maps configuration.');
Exit;
end;
if (config.JsonTypeOf('subscription_key') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid subscription_key.');
Exit;
end;
if (config.StringOfEquals('subscription_key','',1) = 1) then
begin
Memo1.Lines.Add('A nonempty subscription_key is required.');
Exit;
end;
http := TChilkatHttp.Create(Self);
http.RequireSslCertVerify := 1;
http.FollowRedirects := 0;
http.ConnectTimeout := 30;
http.ReadTimeout := 90;
http.Accept := 'application/json';
response := TChilkatHttpResponse.Create(Self);
result := TChilkatJsonObject.Create(Self);
result.Strict := 1;
query := TChilkatJsonObject.Create(Self);
// 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.
resumeOperation := 0;
job := TChilkatJsonObject.Create(Self);
job.Strict := 1;
if (resumeOperation = 1) then
begin
success := job.LoadFile('azure-maps-matrix-operation.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not load saved matrix operation.');
Exit;
end;
if (job.JsonTypeOf('operation_url') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid operation_url.');
Exit;
end;
if (job.StringOfEquals('operation_url','',1) = 1) then
begin
Memo1.Lines.Add('A nonempty operation_url is required.');
Exit;
end;
operationUrl := job.StringOf('operation_url');
end
else
begin
body := TChilkatJsonObject.Create(Self);
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.ControlInterface,'application/geo+json',response.ControlInterface);
// Http methods return false for HTTP errors as well as transport failures.
if (response.StatusCode = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect diagnostics privately; they can contain credentials.');
Exit;
end;
if (response.StatusCode <> 202) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(response.StatusCode));
Memo1.Lines.Add('Error code: ' + response.GetHeaderField('x-ms-error-code'));
Memo1.Lines.Add('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.
Exit;
end;
if (success <> 1) then
begin
Memo1.Lines.Add('The HTTP response was incomplete.');
Exit;
end;
operationUrl := response.GetHeaderField('Operation-Location');
end;
// Validate the polling destination before sending the account key to it.
parsed := TChilkatUrl.Create(Self);
success := parsed.ParseUrl(operationUrl);
if (success <> 1) then
begin
Memo1.Lines.Add('Missing or invalid Operation-Location.');
Exit;
end;
stringCompare.SetString(parsed.Scheme);
stringMatch1 := stringCompare.ContentsEqual('https',1);
stringCompare.SetString(parsed.Host);
stringMatch2 := stringCompare.ContentsEqual('atlas.microsoft.com',1);
stringCompare.SetString(parsed.Login);
stringMatch3 := stringCompare.ContentsEqual('',1);
stringCompare.SetString(parsed.Password);
stringMatch4 := stringCompare.ContentsEqual('',1);
stringCompare.SetString(parsed.Frag);
stringMatch5 := stringCompare.ContentsEqual('',1);
if ((stringMatch1 <> 1) or (stringMatch2 <> 1) or (parsed.Port <> 443) or (stringMatch3 <> 1) or (stringMatch4 <> 1) or (stringMatch5 <> 1)) then
begin
Memo1.Lines.Add('Unexpected operation URL; refusing to send credentials.');
Exit;
end;
pathText := TChilkatStringBuilder.Create(Self);
pathText.Append(parsed.Path);
if (pathText.StartsWith('/route/operations/',1) <> 1) then
begin
Memo1.Lines.Add('Unexpected operation path.');
Exit;
end;
operationId := pathText.GetAfterFinal('/',0);
stringCompare.SetString(operationId);
stringMatch6 := stringCompare.ContentsEqual('',1);
if (stringMatch6 = 1) then
begin
Memo1.Lines.Add('Missing operation ID.');
Exit;
end;
// Treat the ID as text. Rebuild URLs on the fixed Maps host.
success := http.SetUrlVar('operationId',operationId);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not encode operation ID.');
Exit;
end;
job.UpdateString('operation_url',operationUrl);
success := job.WriteFile('azure-maps-matrix-operation.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save the operation for resuming.');
Exit;
end;
Memo1.Lines.Add('Saved matrix operation. Set resumeOperation to true to resume it.');
if (resumeOperation <> 1) then
begin
submitRetryAfter := response.GetHeaderField('Retry-After');
stringCompare.SetString(submitRetryAfter);
stringMatch7 := stringCompare.ContentsEqual('',1);
if (stringMatch7 <> 1) then
begin
Memo1.Lines.Add('Resume after Retry-After: ' + submitRetryAfter);
Exit;
end;
end;
// Do not resubmit a POST automatically after a transport failure: the job may exist.
attempt := 0;
complete := 0;
while ((attempt < 30) and (complete <> 1)) do
begin
// 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.ControlInterface);
// Http methods return false for HTTP errors as well as transport failures.
if (response.StatusCode = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect diagnostics privately; they can contain credentials.');
Exit;
end;
if (response.StatusCode <> 200) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(response.StatusCode));
Memo1.Lines.Add('Error code: ' + response.GetHeaderField('x-ms-error-code'));
Memo1.Lines.Add('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.
Exit;
end;
if (success <> 1) then
begin
Memo1.Lines.Add('The HTTP response was incomplete.');
Exit;
end;
success := result.Load(response.BodyStr);
if (success <> 1) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
if (result.StringOfEquals('status','Completed',1) = 1) then
begin
complete := 1;
end
else
begin
if (result.StringOfEquals('status','Failed',1) = 1) then
begin
Memo1.Lines.Add('Matrix operation failed: ' + result.StringOf('error.code'));
Exit;
end;
if ((result.StringOfEquals('status','Running',1) <> 1) and (result.StringOfEquals('status','NotStarted',1) <> 1)) then
begin
Memo1.Lines.Add('Unexpected operation status.');
Exit;
end;
// If the service supplies Retry-After, defer to the caller's scheduler.
// Preserve the job and resume no sooner than that header permits.
retryAfter := response.GetHeaderField('Retry-After');
stringCompare.SetString(retryAfter);
stringMatch8 := stringCompare.ContentsEqual('',1);
if (stringMatch8 <> 1) then
begin
Memo1.Lines.Add('Resume after Retry-After: ' + retryAfter);
Exit;
end;
end;
attempt := attempt + 1;
end;
if (complete <> 1) then
begin
Memo1.Lines.Add('Polling limit reached; resume the saved operation later.');
Exit;
end;
// 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.ControlInterface);
// Http methods return false for HTTP errors as well as transport failures.
if (response.StatusCode = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect diagnostics privately; they can contain credentials.');
Exit;
end;
if (response.StatusCode <> 200) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(response.StatusCode));
Memo1.Lines.Add('Error code: ' + response.GetHeaderField('x-ms-error-code'));
Memo1.Lines.Add('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.
Exit;
end;
if (success <> 1) then
begin
Memo1.Lines.Add('The HTTP response was incomplete.');
Exit;
end;
success := result.Load(response.BodyStr);
if (success <> 1) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
matrix := TChilkatJsonArray.Create(Self);
cell := TChilkatJsonObject.Create(Self);
success := result.ArrayOf2('properties.matrix',matrix.ControlInterface);
if (success <> 1) then
begin
Memo1.Lines.Add('Expected a matrix array.');
Exit;
end;
if (matrix.Size <> 4) then
begin
Memo1.Lines.Add('Expected four origin/destination results for this 2-by-2 request.');
Exit;
end;
i := 0;
while (i < matrix.Size) do
begin
success := matrix.ObjectAt2(i,cell.ControlInterface);
if (success <> 1) then
begin
Memo1.Lines.Add('Invalid matrix entry.');
Exit;
end;
if (cell.JsonTypeOf('originIndex') <> 2) then
begin
Memo1.Lines.Add('Missing or invalid originIndex.');
Exit;
end;
if (cell.JsonTypeOf('destinationIndex') <> 2) then
begin
Memo1.Lines.Add('Missing or invalid destinationIndex.');
Exit;
end;
if (cell.JsonTypeOf('statusCode') <> 2) then
begin
Memo1.Lines.Add('Missing or invalid statusCode.');
Exit;
end;
// Use the explicit indexes; do not assume matrix entry order.
Memo1.Lines.Add('Origin index: ' + IntToStr(cell.IntOf('originIndex')));
Memo1.Lines.Add('Destination index: ' + IntToStr(cell.IntOf('destinationIndex')));
if (cell.IntOf('statusCode') = 200) then
begin
if (cell.JsonTypeOf('distanceInMeters') <> 2) then
begin
Memo1.Lines.Add('Missing or invalid distanceInMeters.');
Exit;
end;
if (cell.JsonTypeOf('durationInSeconds') <> 2) then
begin
Memo1.Lines.Add('Missing or invalid durationInSeconds.');
Exit;
end;
Memo1.Lines.Add('Distance (meters): ' + cell.StringOf('distanceInMeters'));
Memo1.Lines.Add('Duration (seconds): ' + cell.StringOf('durationInSeconds'));
end
else
begin
Memo1.Lines.Add('Route error: ' + cell.StringOf('error.code'));
end;
i := i + 1;
end;
success := result.WriteFile('azure-maps-matrix.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save matrix result.');
Exit;
end;
Memo1.Lines.Add('Saved azure-maps-matrix.json');