Sample code for 30+ languages & platforms
VBScript 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 VBScript Downloads

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

set stringCompare = CreateObject("Chilkat.StringBuilder")
'  This example requires the Chilkat API to have been previously unlocked.
'  See Global.UnlockBundle for sample code.

set config = CreateObject("Chilkat.JsonObject")
config.Strict = 1
'  Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success = config.LoadFile("qa_data/azure/maps.json")
If (success <> 1) Then
    outFile.WriteLine("Could not load private Azure Maps configuration.")
    WScript.Quit
End If

If (config.JsonTypeOf("subscription_key") <> 1) Then
    outFile.WriteLine("Missing or invalid subscription_key.")
    WScript.Quit
End If

If (config.StringOfEquals("subscription_key","",1) = 1) Then
    outFile.WriteLine("A nonempty subscription_key is required.")
    WScript.Quit
End If

set http = CreateObject("Chilkat.Http")
http.RequireSslCertVerify = 1
http.FollowRedirects = 0
http.ConnectTimeout = 30
http.ReadTimeout = 90
http.Accept = "application/json"
set response = CreateObject("Chilkat.HttpResponse")
set result = CreateObject("Chilkat.JsonObject")
result.Strict = 1
set query = CreateObject("Chilkat.JsonObject")
'  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
set job = CreateObject("Chilkat.JsonObject")
job.Strict = 1

If (resumeOperation = 1) Then
    success = job.LoadFile("azure-maps-matrix-operation.json")
    If (success <> 1) Then
        outFile.WriteLine("Could not load saved matrix operation.")
        WScript.Quit
    End If

    If (job.JsonTypeOf("operation_url") <> 1) Then
        outFile.WriteLine("Missing or invalid operation_url.")
        WScript.Quit
    End If

    If (job.StringOfEquals("operation_url","",1) = 1) Then
        outFile.WriteLine("A nonempty operation_url is required.")
        WScript.Quit
    End If

    operationUrl = job.StringOf("operation_url")
Else
    set body = CreateObject("Chilkat.JsonObject")
    success = body.UpdateString("type","FeatureCollection")
    success = body.UpdateString("features[0].type","Feature")
    success = body.UpdateString("features[0].geometry.type","MultiPoint")
    success = body.UpdateNumber("features[0].geometry.coordinates[0][0]","-122.201399")
    success = body.UpdateNumber("features[0].geometry.coordinates[0][1]","47.608678")
    success = body.UpdateNumber("features[0].geometry.coordinates[1][0]","-122.136833")
    success = body.UpdateNumber("features[0].geometry.coordinates[1][1]","47.642282")
    success = body.UpdateString("features[0].properties.pointType","origins")
    success = body.UpdateString("features[1].type","Feature")
    success = body.UpdateString("features[1].geometry.type","MultiPoint")
    success = body.UpdateNumber("features[1].geometry.coordinates[0][0]","-122.201669")
    success = body.UpdateNumber("features[1].geometry.coordinates[0][1]","47.615076")
    success = body.UpdateNumber("features[1].geometry.coordinates[1][0]","-122.341979")
    success = body.UpdateNumber("features[1].geometry.coordinates[1][1]","47.609525")
    success = body.UpdateString("features[1].properties.pointType","destinations")
    success = body.UpdateString("travelMode","driving")
    success = body.UpdateString("optimizeRoute","fastest")
    success = 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.StatusCode = 0) Then
        outFile.WriteLine("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
        WScript.Quit
    End If

    If (response.StatusCode <> 202) Then
        outFile.WriteLine("HTTP status: " & response.StatusCode)
        outFile.WriteLine("Error code: " & response.GetHeaderField("x-ms-error-code"))
        outFile.WriteLine("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.
        WScript.Quit
    End If

    If (success <> 1) Then
        outFile.WriteLine("The HTTP response was incomplete.")
        WScript.Quit
    End If

    operationUrl = response.GetHeaderField("Operation-Location")
End If

'  Validate the polling destination before sending the account key to it.
set parsed = CreateObject("Chilkat.Url")
success = parsed.ParseUrl(operationUrl)
If (success <> 1) Then
    outFile.WriteLine("Missing or invalid Operation-Location.")
    WScript.Quit
End If

success = stringCompare.SetString(parsed.Scheme)
stringMatch1 = stringCompare.ContentsEqual("https",1)
success = stringCompare.SetString(parsed.Host)
stringMatch2 = stringCompare.ContentsEqual("atlas.microsoft.com",1)
success = stringCompare.SetString(parsed.Login)
stringMatch3 = stringCompare.ContentsEqual("",1)
success = stringCompare.SetString(parsed.Password)
stringMatch4 = stringCompare.ContentsEqual("",1)
success = 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
    outFile.WriteLine("Unexpected operation URL; refusing to send credentials.")
    WScript.Quit
End If

set pathText = CreateObject("Chilkat.StringBuilder")
success = pathText.Append(parsed.Path)
If (pathText.StartsWith("/route/operations/",1) <> 1) Then
    outFile.WriteLine("Unexpected operation path.")
    WScript.Quit
End If

operationId = pathText.GetAfterFinal("/",0)
success = stringCompare.SetString(operationId)
stringMatch6 = stringCompare.ContentsEqual("",1)
If (stringMatch6 = 1) Then
    outFile.WriteLine("Missing operation ID.")
    WScript.Quit
End If

'  Treat the ID as text. Rebuild URLs on the fixed Maps host.
success = http.SetUrlVar("operationId",operationId)
If (success <> 1) Then
    outFile.WriteLine("Could not encode operation ID.")
    WScript.Quit
End If

success = job.UpdateString("operation_url",operationUrl)
success = job.WriteFile("azure-maps-matrix-operation.json")
If (success <> 1) Then
    outFile.WriteLine("Could not save the operation for resuming.")
    WScript.Quit
End If

outFile.WriteLine("Saved matrix operation. Set resumeOperation to true to resume it.")
If (resumeOperation <> 1) Then
    submitRetryAfter = response.GetHeaderField("Retry-After")
    success = stringCompare.SetString(submitRetryAfter)
    stringMatch7 = stringCompare.ContentsEqual("",1)
    If (stringMatch7 <> 1) Then
        outFile.WriteLine("Resume after Retry-After: " & submitRetryAfter)
        WScript.Quit
    End If

End If

'  Do not resubmit a POST automatically after a transport failure: the job may exist.
attempt = 0
complete = 0
Do While ((attempt < 30) And (complete <> 1))
    '  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.StatusCode = 0) Then
        outFile.WriteLine("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
        WScript.Quit
    End If

    If (response.StatusCode <> 200) Then
        outFile.WriteLine("HTTP status: " & response.StatusCode)
        outFile.WriteLine("Error code: " & response.GetHeaderField("x-ms-error-code"))
        outFile.WriteLine("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.
        WScript.Quit
    End If

    If (success <> 1) Then
        outFile.WriteLine("The HTTP response was incomplete.")
        WScript.Quit
    End If

    success = result.Load(response.BodyStr)
    If (success <> 1) Then
        outFile.WriteLine("Expected a well-formed JSON response.")
        WScript.Quit
    End If

    If (result.StringOfEquals("status","Completed",1) = 1) Then
        complete = 1
    Else
        If (result.StringOfEquals("status","Failed",1) = 1) Then
            outFile.WriteLine("Matrix operation failed: " & result.StringOf("error.code"))
            WScript.Quit
        End If

        If ((result.StringOfEquals("status","Running",1) <> 1) And (result.StringOfEquals("status","NotStarted",1) <> 1)) Then
            outFile.WriteLine("Unexpected operation status.")
            WScript.Quit
        End If

        '  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")
        success = stringCompare.SetString(retryAfter)
        stringMatch8 = stringCompare.ContentsEqual("",1)
        If (stringMatch8 <> 1) Then
            outFile.WriteLine("Resume after Retry-After: " & retryAfter)
            WScript.Quit
        End If

    End If

    attempt = attempt + 1
Loop
If (complete <> 1) Then
    outFile.WriteLine("Polling limit reached; resume the saved operation later.")
    WScript.Quit
End If

'  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.StatusCode = 0) Then
    outFile.WriteLine("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
    WScript.Quit
End If

If (response.StatusCode <> 200) Then
    outFile.WriteLine("HTTP status: " & response.StatusCode)
    outFile.WriteLine("Error code: " & response.GetHeaderField("x-ms-error-code"))
    outFile.WriteLine("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.
    WScript.Quit
End If

If (success <> 1) Then
    outFile.WriteLine("The HTTP response was incomplete.")
    WScript.Quit
End If

success = result.Load(response.BodyStr)
If (success <> 1) Then
    outFile.WriteLine("Expected a well-formed JSON response.")
    WScript.Quit
End If

set matrix = CreateObject("Chilkat.JsonArray")
set cell = CreateObject("Chilkat.JsonObject")
success = result.ArrayOf2("properties.matrix",matrix)
If (success <> 1) Then
    outFile.WriteLine("Expected a matrix array.")
    WScript.Quit
End If

If (matrix.Size <> 4) Then
    outFile.WriteLine("Expected four origin/destination results for this 2-by-2 request.")
    WScript.Quit
End If

i = 0
Do While (i < matrix.Size)
    success = matrix.ObjectAt2(i,cell)
    If (success <> 1) Then
        outFile.WriteLine("Invalid matrix entry.")
        WScript.Quit
    End If

    If (cell.JsonTypeOf("originIndex") <> 2) Then
        outFile.WriteLine("Missing or invalid originIndex.")
        WScript.Quit
    End If

    If (cell.JsonTypeOf("destinationIndex") <> 2) Then
        outFile.WriteLine("Missing or invalid destinationIndex.")
        WScript.Quit
    End If

    If (cell.JsonTypeOf("statusCode") <> 2) Then
        outFile.WriteLine("Missing or invalid statusCode.")
        WScript.Quit
    End If

    '  Use the explicit indexes; do not assume matrix entry order.
    outFile.WriteLine("Origin index: " & cell.IntOf("originIndex"))
    outFile.WriteLine("Destination index: " & cell.IntOf("destinationIndex"))
    If (cell.IntOf("statusCode") = 200) Then
        If (cell.JsonTypeOf("distanceInMeters") <> 2) Then
            outFile.WriteLine("Missing or invalid distanceInMeters.")
            WScript.Quit
        End If

        If (cell.JsonTypeOf("durationInSeconds") <> 2) Then
            outFile.WriteLine("Missing or invalid durationInSeconds.")
            WScript.Quit
        End If

        outFile.WriteLine("Distance (meters): " & cell.StringOf("distanceInMeters"))
        outFile.WriteLine("Duration (seconds): " & cell.StringOf("durationInSeconds"))
    Else
        outFile.WriteLine("Route error: " & cell.StringOf("error.code"))
    End If

    i = i + 1
Loop
success = result.WriteFile("azure-maps-matrix.json")
If (success <> 1) Then
    outFile.WriteLine("Could not save matrix result.")
    WScript.Quit
End If

outFile.WriteLine("Saved azure-maps-matrix.json")

outFile.Close