Sample code for 30+ languages & platforms
AutoIt Requires Chilkat v11.6.0+

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.

Microsoft API reference

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

$oStringCompare = ObjCreate("Chilkat.StringBuilder")
;  This example requires the Chilkat API to have been previously unlocked.
;  See Global.UnlockBundle for sample code.

$oConfig = ObjCreate("Chilkat.JsonObject")
$oConfig.Strict = True
;  Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
$bSuccess = $oConfig.LoadFile("qa_data/azure/maps.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load private Azure Maps configuration." & @CRLF)
    Exit
EndIf

If ($oConfig.JsonTypeOf("subscription_key") <> 1) Then
    ConsoleWrite("Missing or invalid subscription_key." & @CRLF)
    Exit
EndIf

If ($oConfig.StringOfEquals("subscription_key","",True) = True) Then
    ConsoleWrite("A nonempty subscription_key is required." & @CRLF)
    Exit
EndIf

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 30
$oHttp.ReadTimeout = 90
$oHttp.Accept = "application/json"
$oResponse = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oQuery = ObjCreate("Chilkat.JsonObject")
;  Current Azure Maps operations accept the key as a header.
$oHttp.SetRequestHeader "subscription-key",$oConfig.StringOf("subscription_key")
;  Set true to resume the saved operation instead of submitting another job.
Local $bResumeOperation = False
$oJob = ObjCreate("Chilkat.JsonObject")
$oJob.Strict = True
Local $sOperationUrl
If ($bResumeOperation = True) Then
    $bSuccess = $oJob.LoadFile("azure-maps-matrix-operation.json")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not load saved matrix operation." & @CRLF)
        Exit
    EndIf

    If ($oJob.JsonTypeOf("operation_url") <> 1) Then
        ConsoleWrite("Missing or invalid operation_url." & @CRLF)
        Exit
    EndIf

    If ($oJob.StringOfEquals("operation_url","",True) = True) Then
        ConsoleWrite("A nonempty operation_url is required." & @CRLF)
        Exit
    EndIf

    $sOperationUrl = $oJob.StringOf("operation_url")
Else
    $oBody = ObjCreate("Chilkat.JsonObject")
    $oBody.UpdateString("type","FeatureCollection")
    $oBody.UpdateString("features[0].type","Feature")
    $oBody.UpdateString("features[0].geometry.type","MultiPoint")
    $oBody.UpdateNumber("features[0].geometry.coordinates[0][0]","-122.201399")
    $oBody.UpdateNumber("features[0].geometry.coordinates[0][1]","47.608678")
    $oBody.UpdateNumber("features[0].geometry.coordinates[1][0]","-122.136833")
    $oBody.UpdateNumber("features[0].geometry.coordinates[1][1]","47.642282")
    $oBody.UpdateString("features[0].properties.pointType","origins")
    $oBody.UpdateString("features[1].type","Feature")
    $oBody.UpdateString("features[1].geometry.type","MultiPoint")
    $oBody.UpdateNumber("features[1].geometry.coordinates[0][0]","-122.201669")
    $oBody.UpdateNumber("features[1].geometry.coordinates[0][1]","47.615076")
    $oBody.UpdateNumber("features[1].geometry.coordinates[1][0]","-122.341979")
    $oBody.UpdateNumber("features[1].geometry.coordinates[1][1]","47.609525")
    $oBody.UpdateString("features[1].properties.pointType","destinations")
    $oBody.UpdateString("travelMode","driving")
    $oBody.UpdateString("optimizeRoute","fastest")
    $oBody.UpdateString("traffic","historical")
    $bSuccess = $oHttp.HttpJson("POST","https://atlas.microsoft.com/route/matrix:async?api-version=2025-01-01",$oBody,"application/geo+json",$oResponse)
    ;  Http methods return false for HTTP errors as well as transport failures.
    If ($oResponse.StatusCode = 0) Then
        ConsoleWrite("No HTTP response. Inspect diagnostics privately; they can contain credentials." & @CRLF)
        Exit
    EndIf

    If ($oResponse.StatusCode <> 202) Then
        ConsoleWrite("HTTP status: " & $oResponse.StatusCode & @CRLF)
        ConsoleWrite("Error code: " & $oResponse.GetHeaderField("x-ms-error-code") & @CRLF)
        ConsoleWrite("Retry-After: " & $oResponse.GetHeaderField("Retry-After") & @CRLF)
        ;  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
    EndIf

    If ($bSuccess <> True) Then
        ConsoleWrite("The HTTP response was incomplete." & @CRLF)
        Exit
    EndIf

    $sOperationUrl = $oResponse.GetHeaderField("Operation-Location")
EndIf

;  Validate the polling destination before sending the account key to it.
$oParsed = ObjCreate("Chilkat.Url")
$bSuccess = $oParsed.ParseUrl($sOperationUrl)
If ($bSuccess <> True) Then
    ConsoleWrite("Missing or invalid Operation-Location." & @CRLF)
    Exit
EndIf

$oStringCompare.SetString($oParsed.Scheme)
Local $bStringMatch1 = $oStringCompare.ContentsEqual("https",True)
$oStringCompare.SetString($oParsed.Host)
Local $bStringMatch2 = $oStringCompare.ContentsEqual("atlas.microsoft.com",True)
$oStringCompare.SetString($oParsed.Login)
Local $bStringMatch3 = $oStringCompare.ContentsEqual("",True)
$oStringCompare.SetString($oParsed.Password)
Local $bStringMatch4 = $oStringCompare.ContentsEqual("",True)
$oStringCompare.SetString($oParsed.Frag)
Local $bStringMatch5 = $oStringCompare.ContentsEqual("",True)
If (($bStringMatch1 <> True) Or ($bStringMatch2 <> True) Or ($oParsed.Port <> 443) Or ($bStringMatch3 <> True) Or ($bStringMatch4 <> True) Or ($bStringMatch5 <> True)) Then
    ConsoleWrite("Unexpected operation URL; refusing to send credentials." & @CRLF)
    Exit
EndIf

$oPathText = ObjCreate("Chilkat.StringBuilder")
$oPathText.Append($oParsed.Path)
If ($oPathText.StartsWith("/route/operations/",True) <> True) Then
    ConsoleWrite("Unexpected operation path." & @CRLF)
    Exit
EndIf

Local $sOperationId = $oPathText.GetAfterFinal("/",False)
$oStringCompare.SetString($sOperationId)
Local $bStringMatch6 = $oStringCompare.ContentsEqual("",True)
If ($bStringMatch6 = True) Then
    ConsoleWrite("Missing operation ID." & @CRLF)
    Exit
EndIf

;  Treat the ID as text. Rebuild URLs on the fixed Maps host.
$bSuccess = $oHttp.SetUrlVar("operationId",$sOperationId)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not encode operation ID." & @CRLF)
    Exit
EndIf

$oJob.UpdateString("operation_url",$sOperationUrl)
$bSuccess = $oJob.WriteFile("azure-maps-matrix-operation.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save the operation for resuming." & @CRLF)
    Exit
EndIf

ConsoleWrite("Saved matrix operation. Set resumeOperation to true to resume it." & @CRLF)
If ($bResumeOperation <> True) Then
Local $submitRetryAfter = $oResponse.GetHeaderField("Retry-After")
    $oStringCompare.SetString($submitRetryAfter)
Local $bStringMatch7 = $oStringCompare.ContentsEqual("",True)
    If ($bStringMatch7 <> True) Then
        ConsoleWrite("Resume after Retry-After: " & $submitRetryAfter & @CRLF)
        Exit
    EndIf

EndIf

;  Do not resubmit a POST automatically after a transport failure: the job may exist.
Local $iAttempt = 0
Local $bComplete = False
While (($iAttempt < 30) And ($bComplete <> True))
    ;  A short example limit. A production worker should schedule polling off the UI thread.
    $oHttp.SleepMs 2000
    $bSuccess = $oHttp.HttpNoBody("GET","https://atlas.microsoft.com/route/operations/{$operationId}?api-version=2025-01-01",$oResponse)
    ;  Http methods return false for HTTP errors as well as transport failures.
    If ($oResponse.StatusCode = 0) Then
        ConsoleWrite("No HTTP response. Inspect diagnostics privately; they can contain credentials." & @CRLF)
        Exit
    EndIf

    If ($oResponse.StatusCode <> 200) Then
        ConsoleWrite("HTTP status: " & $oResponse.StatusCode & @CRLF)
        ConsoleWrite("Error code: " & $oResponse.GetHeaderField("x-ms-error-code") & @CRLF)
        ConsoleWrite("Retry-After: " & $oResponse.GetHeaderField("Retry-After") & @CRLF)
        ;  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
    EndIf

    If ($bSuccess <> True) Then
        ConsoleWrite("The HTTP response was incomplete." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oResult.Load($oResponse.BodyStr)
    If ($bSuccess <> True) Then
        ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
        Exit
    EndIf

    If ($oResult.StringOfEquals("status","Completed",True) = True) Then
        $bComplete = True
    Else
        If ($oResult.StringOfEquals("status","Failed",True) = True) Then
            ConsoleWrite("Matrix operation failed: " & $oResult.StringOf("error.code") & @CRLF)
            Exit
        EndIf

        If (($oResult.StringOfEquals("status","Running",True) <> True) And ($oResult.StringOfEquals("status","NotStarted",True) <> True)) Then
            ConsoleWrite("Unexpected operation status." & @CRLF)
            Exit
        EndIf

        ;  If the service supplies Retry-After, defer to the caller's scheduler.
        ;  Preserve the job and resume no sooner than that header permits.
Local $sRetryAfter = $oResponse.GetHeaderField("Retry-After")
        $oStringCompare.SetString($sRetryAfter)
Local $bStringMatch8 = $oStringCompare.ContentsEqual("",True)
        If ($bStringMatch8 <> True) Then
            ConsoleWrite("Resume after Retry-After: " & $sRetryAfter & @CRLF)
            Exit
        EndIf

    EndIf

    $iAttempt = $iAttempt + 1
Wend
If ($bComplete <> True) Then
    ConsoleWrite("Polling limit reached; resume the saved operation later." & @CRLF)
    Exit
EndIf

;  Use the documented result endpoint on the same fixed host.
$bSuccess = $oHttp.HttpNoBody("GET","https://atlas.microsoft.com/route/operations/{$operationId}/result?api-version=2025-01-01",$oResponse)
;  Http methods return false for HTTP errors as well as transport failures.
If ($oResponse.StatusCode = 0) Then
    ConsoleWrite("No HTTP response. Inspect diagnostics privately; they can contain credentials." & @CRLF)
    Exit
EndIf

If ($oResponse.StatusCode <> 200) Then
    ConsoleWrite("HTTP status: " & $oResponse.StatusCode & @CRLF)
    ConsoleWrite("Error code: " & $oResponse.GetHeaderField("x-ms-error-code") & @CRLF)
    ConsoleWrite("Retry-After: " & $oResponse.GetHeaderField("Retry-After") & @CRLF)
    ;  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
EndIf

If ($bSuccess <> True) Then
    ConsoleWrite("The HTTP response was incomplete." & @CRLF)
    Exit
EndIf

$bSuccess = $oResult.Load($oResponse.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
    Exit
EndIf

$oMatrix = ObjCreate("Chilkat.JsonArray")
$oCell = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oResult.ArrayOf2("properties.matrix",$oMatrix)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected a matrix array." & @CRLF)
    Exit
EndIf

If ($oMatrix.Size <> 4) Then
    ConsoleWrite("Expected four origin/destination results for this 2-by-2 request." & @CRLF)
    Exit
EndIf

Local $i = 0
While ($i < $oMatrix.Size)
    $bSuccess = $oMatrix.ObjectAt2($i,$oCell)
    If ($bSuccess <> True) Then
        ConsoleWrite("Invalid matrix entry." & @CRLF)
        Exit
    EndIf

    If ($oCell.JsonTypeOf("originIndex") <> 2) Then
        ConsoleWrite("Missing or invalid originIndex." & @CRLF)
        Exit
    EndIf

    If ($oCell.JsonTypeOf("destinationIndex") <> 2) Then
        ConsoleWrite("Missing or invalid destinationIndex." & @CRLF)
        Exit
    EndIf

    If ($oCell.JsonTypeOf("statusCode") <> 2) Then
        ConsoleWrite("Missing or invalid statusCode." & @CRLF)
        Exit
    EndIf

    ;  Use the explicit indexes; do not assume matrix entry order.
    ConsoleWrite("Origin index: " & $oCell.IntOf("originIndex") & @CRLF)
    ConsoleWrite("Destination index: " & $oCell.IntOf("destinationIndex") & @CRLF)
    If ($oCell.IntOf("statusCode") = 200) Then
        If ($oCell.JsonTypeOf("distanceInMeters") <> 2) Then
            ConsoleWrite("Missing or invalid distanceInMeters." & @CRLF)
            Exit
        EndIf

        If ($oCell.JsonTypeOf("durationInSeconds") <> 2) Then
            ConsoleWrite("Missing or invalid durationInSeconds." & @CRLF)
            Exit
        EndIf

        ConsoleWrite("Distance (meters): " & $oCell.StringOf("distanceInMeters") & @CRLF)
        ConsoleWrite("Duration (seconds): " & $oCell.StringOf("durationInSeconds") & @CRLF)
    Else
        ConsoleWrite("Route error: " & $oCell.StringOf("error.code") & @CRLF)
    EndIf

    $i = $i + 1
Wend
$bSuccess = $oResult.WriteFile("azure-maps-matrix.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save matrix result." & @CRLF)
    Exit
EndIf

ConsoleWrite("Saved azure-maps-matrix.json" & @CRLF)