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 DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoStringCompare
Handle hoConfig
Handle hoHttp
Variant vResponse
Handle hoResponse
Handle hoResult
Handle hoQuery
Boolean iResumeOperation
Handle hoJob
String sOperationUrl
Variant vBody
Handle hoBody
Handle hoParsed
Boolean iStringMatch1
Boolean iStringMatch2
Boolean iStringMatch3
Boolean iStringMatch4
Boolean iStringMatch5
Handle hoPathText
String sOperationId
Boolean iStringMatch6
String sSubmitRetryAfter
Boolean iStringMatch7
Integer iAttempt
Boolean iComplete
String sRetryAfter
Boolean iStringMatch8
Variant vMatrix
Handle hoMatrix
Variant vCell
Handle hoCell
Integer i
String sTemp1
Integer iTemp1
Boolean bTemp1
Boolean bTemp2
Move False To iSuccess
Get Create (RefClass(cComChilkatStringBuilder)) To hoStringCompare
If (Not(IsComObjectCreated(hoStringCompare))) Begin
Send CreateComObject of hoStringCompare
End
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
Get Create (RefClass(cComChilkatJsonObject)) To hoConfig
If (Not(IsComObjectCreated(hoConfig))) Begin
Send CreateComObject of hoConfig
End
Set ComStrict Of hoConfig To True
// Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
Get ComLoadFile Of hoConfig "qa_data/azure/maps.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not load private Azure Maps configuration."
Procedure_Return
End
Get ComJsonTypeOf Of hoConfig "subscription_key" To iTemp1
If (iTemp1 <> 1) Begin
Showln "Missing or invalid subscription_key."
Procedure_Return
End
Get ComStringOfEquals Of hoConfig "subscription_key" "" True To bTemp1
If (bTemp1 = True) Begin
Showln "A nonempty subscription_key is required."
Procedure_Return
End
Get Create (RefClass(cComChilkatHttp)) To hoHttp
If (Not(IsComObjectCreated(hoHttp))) Begin
Send CreateComObject of hoHttp
End
Set ComRequireSslCertVerify Of hoHttp To True
Set ComFollowRedirects Of hoHttp To False
Set ComConnectTimeout Of hoHttp To 30
Set ComReadTimeout Of hoHttp To 90
Set ComAccept Of hoHttp To "application/json"
Get Create (RefClass(cComChilkatHttpResponse)) To hoResponse
If (Not(IsComObjectCreated(hoResponse))) Begin
Send CreateComObject of hoResponse
End
Get Create (RefClass(cComChilkatJsonObject)) To hoResult
If (Not(IsComObjectCreated(hoResult))) Begin
Send CreateComObject of hoResult
End
Set ComStrict Of hoResult To True
Get Create (RefClass(cComChilkatJsonObject)) To hoQuery
If (Not(IsComObjectCreated(hoQuery))) Begin
Send CreateComObject of hoQuery
End
// Current Azure Maps operations accept the key as a header.
Get ComStringOf Of hoConfig "subscription_key" To sTemp1
Send ComSetRequestHeader To hoHttp "subscription-key" sTemp1
// Set true to resume the saved operation instead of submitting another job.
Move False To iResumeOperation
Get Create (RefClass(cComChilkatJsonObject)) To hoJob
If (Not(IsComObjectCreated(hoJob))) Begin
Send CreateComObject of hoJob
End
Set ComStrict Of hoJob To True
If (iResumeOperation = True) Begin
Get ComLoadFile Of hoJob "azure-maps-matrix-operation.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not load saved matrix operation."
Procedure_Return
End
Get ComJsonTypeOf Of hoJob "operation_url" To iTemp1
If (iTemp1 <> 1) Begin
Showln "Missing or invalid operation_url."
Procedure_Return
End
Get ComStringOfEquals Of hoJob "operation_url" "" True To bTemp1
If (bTemp1 = True) Begin
Showln "A nonempty operation_url is required."
Procedure_Return
End
Get ComStringOf Of hoJob "operation_url" To sOperationUrl
End
Else Begin
Get Create (RefClass(cComChilkatJsonObject)) To hoBody
If (Not(IsComObjectCreated(hoBody))) Begin
Send CreateComObject of hoBody
End
Get ComUpdateString Of hoBody "type" "FeatureCollection" To iSuccess
Get ComUpdateString Of hoBody "features[0].type" "Feature" To iSuccess
Get ComUpdateString Of hoBody "features[0].geometry.type" "MultiPoint" To iSuccess
Get ComUpdateNumber Of hoBody "features[0].geometry.coordinates[0][0]" "-122.201399" To iSuccess
Get ComUpdateNumber Of hoBody "features[0].geometry.coordinates[0][1]" "47.608678" To iSuccess
Get ComUpdateNumber Of hoBody "features[0].geometry.coordinates[1][0]" "-122.136833" To iSuccess
Get ComUpdateNumber Of hoBody "features[0].geometry.coordinates[1][1]" "47.642282" To iSuccess
Get ComUpdateString Of hoBody "features[0].properties.pointType" "origins" To iSuccess
Get ComUpdateString Of hoBody "features[1].type" "Feature" To iSuccess
Get ComUpdateString Of hoBody "features[1].geometry.type" "MultiPoint" To iSuccess
Get ComUpdateNumber Of hoBody "features[1].geometry.coordinates[0][0]" "-122.201669" To iSuccess
Get ComUpdateNumber Of hoBody "features[1].geometry.coordinates[0][1]" "47.615076" To iSuccess
Get ComUpdateNumber Of hoBody "features[1].geometry.coordinates[1][0]" "-122.341979" To iSuccess
Get ComUpdateNumber Of hoBody "features[1].geometry.coordinates[1][1]" "47.609525" To iSuccess
Get ComUpdateString Of hoBody "features[1].properties.pointType" "destinations" To iSuccess
Get ComUpdateString Of hoBody "travelMode" "driving" To iSuccess
Get ComUpdateString Of hoBody "optimizeRoute" "fastest" To iSuccess
Get ComUpdateString Of hoBody "traffic" "historical" To iSuccess
Get pvComObject of hoBody to vBody
Get pvComObject of hoResponse to vResponse
Get ComHttpJson Of hoHttp "POST" "https://atlas.microsoft.com/route/matrix:async?api-version=2025-01-01" vBody "application/geo+json" vResponse To iSuccess
// Http methods return false for HTTP errors as well as transport failures.
Get ComStatusCode Of hoResponse To iTemp1
If (iTemp1 = 0) Begin
Showln "No HTTP response. Inspect diagnostics privately; they can contain credentials."
Procedure_Return
End
Get ComStatusCode Of hoResponse To iTemp1
If (iTemp1 <> 202) Begin
Get ComStatusCode Of hoResponse To iTemp1
Showln "HTTP status: " iTemp1
Get ComGetHeaderField Of hoResponse "x-ms-error-code" To sTemp1
Showln "Error code: " sTemp1
Get ComGetHeaderField Of hoResponse "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
// Correct 400/401/403 errors before retrying. Back off for 429 and transient 5xx.
// Keep response bodies and detailed diagnostics out of public logs.
Procedure_Return
End
If (iSuccess <> True) Begin
Showln "The HTTP response was incomplete."
Procedure_Return
End
Get ComGetHeaderField Of hoResponse "Operation-Location" To sOperationUrl
End
// Validate the polling destination before sending the account key to it.
Get Create (RefClass(cComChilkatUrl)) To hoParsed
If (Not(IsComObjectCreated(hoParsed))) Begin
Send CreateComObject of hoParsed
End
Get ComParseUrl Of hoParsed sOperationUrl To iSuccess
If (iSuccess <> True) Begin
Showln "Missing or invalid Operation-Location."
Procedure_Return
End
Get ComScheme Of hoParsed To sTemp1
Get ComSetString Of hoStringCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoStringCompare "https" True To iStringMatch1
Get ComHost Of hoParsed To sTemp1
Get ComSetString Of hoStringCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoStringCompare "atlas.microsoft.com" True To iStringMatch2
Get ComLogin Of hoParsed To sTemp1
Get ComSetString Of hoStringCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoStringCompare "" True To iStringMatch3
Get ComPassword Of hoParsed To sTemp1
Get ComSetString Of hoStringCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoStringCompare "" True To iStringMatch4
Get ComFrag Of hoParsed To sTemp1
Get ComSetString Of hoStringCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoStringCompare "" True To iStringMatch5
Get ComPort Of hoParsed To iTemp1
If ((iStringMatch1 <> True) Or (iStringMatch2 <> True) Or (iTemp1 <> 443) Or (iStringMatch3 <> True) Or (iStringMatch4 <> True) Or (iStringMatch5 <> True)) Begin
Showln "Unexpected operation URL; refusing to send credentials."
Procedure_Return
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoPathText
If (Not(IsComObjectCreated(hoPathText))) Begin
Send CreateComObject of hoPathText
End
Get ComPath Of hoParsed To sTemp1
Get ComAppend Of hoPathText sTemp1 To iSuccess
Get ComStartsWith Of hoPathText "/route/operations/" True To bTemp1
If (bTemp1 <> True) Begin
Showln "Unexpected operation path."
Procedure_Return
End
Get ComGetAfterFinal Of hoPathText "/" False To sOperationId
Get ComSetString Of hoStringCompare sOperationId To iSuccess
Get ComContentsEqual Of hoStringCompare "" True To iStringMatch6
If (iStringMatch6 = True) Begin
Showln "Missing operation ID."
Procedure_Return
End
// Treat the ID as text. Rebuild URLs on the fixed Maps host.
Get ComSetUrlVar Of hoHttp "operationId" sOperationId To iSuccess
If (iSuccess <> True) Begin
Showln "Could not encode operation ID."
Procedure_Return
End
Get ComUpdateString Of hoJob "operation_url" sOperationUrl To iSuccess
Get ComWriteFile Of hoJob "azure-maps-matrix-operation.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not save the operation for resuming."
Procedure_Return
End
Showln "Saved matrix operation. Set resumeOperation to true to resume it."
If (iResumeOperation <> True) Begin
Get ComGetHeaderField Of hoResponse "Retry-After" To sSubmitRetryAfter
Get ComSetString Of hoStringCompare sSubmitRetryAfter To iSuccess
Get ComContentsEqual Of hoStringCompare "" True To iStringMatch7
If (iStringMatch7 <> True) Begin
Showln "Resume after Retry-After: " sSubmitRetryAfter
Procedure_Return
End
End
// Do not resubmit a POST automatically after a transport failure: the job may exist.
Move 0 To iAttempt
Move False To iComplete
While ((iAttempt < 30) And (iComplete <> True))
// A short example limit. A production worker should schedule polling off the UI thread.
Send ComSleepMs To hoHttp 2000
Get pvComObject of hoResponse to vResponse
Get ComHttpNoBody Of hoHttp "GET" "https://atlas.microsoft.com/route/operations/{$operationId}?api-version=2025-01-01" vResponse To iSuccess
// Http methods return false for HTTP errors as well as transport failures.
Get ComStatusCode Of hoResponse To iTemp1
If (iTemp1 = 0) Begin
Showln "No HTTP response. Inspect diagnostics privately; they can contain credentials."
Procedure_Return
End
Get ComStatusCode Of hoResponse To iTemp1
If (iTemp1 <> 200) Begin
Get ComStatusCode Of hoResponse To iTemp1
Showln "HTTP status: " iTemp1
Get ComGetHeaderField Of hoResponse "x-ms-error-code" To sTemp1
Showln "Error code: " sTemp1
Get ComGetHeaderField Of hoResponse "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
// Correct 400/401/403 errors before retrying. Back off for 429 and transient 5xx.
// Keep response bodies and detailed diagnostics out of public logs.
Procedure_Return
End
If (iSuccess <> True) Begin
Showln "The HTTP response was incomplete."
Procedure_Return
End
Get ComBodyStr Of hoResponse To sTemp1
Get ComLoad Of hoResult sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get ComStringOfEquals Of hoResult "status" "Completed" True To bTemp1
If (bTemp1 = True) Begin
Move True To iComplete
End
Else Begin
Get ComStringOfEquals Of hoResult "status" "Failed" True To bTemp1
If (bTemp1 = True) Begin
Get ComStringOf Of hoResult "error.code" To sTemp1
Showln "Matrix operation failed: " sTemp1
Procedure_Return
End
Get ComStringOfEquals Of hoResult "status" "Running" True To bTemp1
Get ComStringOfEquals Of hoResult "status" "NotStarted" True To bTemp2
If ((bTemp1 <> True) And (bTemp2 <> True)) Begin
Showln "Unexpected operation status."
Procedure_Return
End
// If the service supplies Retry-After, defer to the caller's scheduler.
// Preserve the job and resume no sooner than that header permits.
Get ComGetHeaderField Of hoResponse "Retry-After" To sRetryAfter
Get ComSetString Of hoStringCompare sRetryAfter To iSuccess
Get ComContentsEqual Of hoStringCompare "" True To iStringMatch8
If (iStringMatch8 <> True) Begin
Showln "Resume after Retry-After: " sRetryAfter
Procedure_Return
End
End
Move (iAttempt + 1) To iAttempt
Loop
If (iComplete <> True) Begin
Showln "Polling limit reached; resume the saved operation later."
Procedure_Return
End
// Use the documented result endpoint on the same fixed host.
Get pvComObject of hoResponse to vResponse
Get ComHttpNoBody Of hoHttp "GET" "https://atlas.microsoft.com/route/operations/{$operationId}/result?api-version=2025-01-01" vResponse To iSuccess
// Http methods return false for HTTP errors as well as transport failures.
Get ComStatusCode Of hoResponse To iTemp1
If (iTemp1 = 0) Begin
Showln "No HTTP response. Inspect diagnostics privately; they can contain credentials."
Procedure_Return
End
Get ComStatusCode Of hoResponse To iTemp1
If (iTemp1 <> 200) Begin
Get ComStatusCode Of hoResponse To iTemp1
Showln "HTTP status: " iTemp1
Get ComGetHeaderField Of hoResponse "x-ms-error-code" To sTemp1
Showln "Error code: " sTemp1
Get ComGetHeaderField Of hoResponse "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
// Correct 400/401/403 errors before retrying. Back off for 429 and transient 5xx.
// Keep response bodies and detailed diagnostics out of public logs.
Procedure_Return
End
If (iSuccess <> True) Begin
Showln "The HTTP response was incomplete."
Procedure_Return
End
Get ComBodyStr Of hoResponse To sTemp1
Get ComLoad Of hoResult sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get Create (RefClass(cComChilkatJsonArray)) To hoMatrix
If (Not(IsComObjectCreated(hoMatrix))) Begin
Send CreateComObject of hoMatrix
End
Get Create (RefClass(cComChilkatJsonObject)) To hoCell
If (Not(IsComObjectCreated(hoCell))) Begin
Send CreateComObject of hoCell
End
Get pvComObject of hoMatrix to vMatrix
Get ComArrayOf2 Of hoResult "properties.matrix" vMatrix To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a matrix array."
Procedure_Return
End
Get ComSize Of hoMatrix To iTemp1
If (iTemp1 <> 4) Begin
Showln "Expected four origin/destination results for this 2-by-2 request."
Procedure_Return
End
Move 0 To i
While (i < (ComSize(hoMatrix)))
Get pvComObject of hoCell to vCell
Get ComObjectAt2 Of hoMatrix i vCell To iSuccess
If (iSuccess <> True) Begin
Showln "Invalid matrix entry."
Procedure_Return
End
Get ComJsonTypeOf Of hoCell "originIndex" To iTemp1
If (iTemp1 <> 2) Begin
Showln "Missing or invalid originIndex."
Procedure_Return
End
Get ComJsonTypeOf Of hoCell "destinationIndex" To iTemp1
If (iTemp1 <> 2) Begin
Showln "Missing or invalid destinationIndex."
Procedure_Return
End
Get ComJsonTypeOf Of hoCell "statusCode" To iTemp1
If (iTemp1 <> 2) Begin
Showln "Missing or invalid statusCode."
Procedure_Return
End
// Use the explicit indexes; do not assume matrix entry order.
Get ComIntOf Of hoCell "originIndex" To iTemp1
Showln "Origin index: " iTemp1
Get ComIntOf Of hoCell "destinationIndex" To iTemp1
Showln "Destination index: " iTemp1
Get ComIntOf Of hoCell "statusCode" To iTemp1
If (iTemp1 = 200) Begin
Get ComJsonTypeOf Of hoCell "distanceInMeters" To iTemp1
If (iTemp1 <> 2) Begin
Showln "Missing or invalid distanceInMeters."
Procedure_Return
End
Get ComJsonTypeOf Of hoCell "durationInSeconds" To iTemp1
If (iTemp1 <> 2) Begin
Showln "Missing or invalid durationInSeconds."
Procedure_Return
End
Get ComStringOf Of hoCell "distanceInMeters" To sTemp1
Showln "Distance (meters): " sTemp1
Get ComStringOf Of hoCell "durationInSeconds" To sTemp1
Showln "Duration (seconds): " sTemp1
End
Else Begin
Get ComStringOf Of hoCell "error.code" To sTemp1
Showln "Route error: " sTemp1
End
Move (i + 1) To i
Loop
Get ComWriteFile Of hoResult "azure-maps-matrix.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not save matrix result."
Procedure_Return
End
Showln "Saved azure-maps-matrix.json"
End_Procedure