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 Xojo Plugin Downloads
Dim success As Boolean
success = False
Dim stringCompare As New Chilkat.StringBuilder
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
Dim config As New Chilkat.JsonObject
config.Strict = True
// Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success = config.LoadFile("qa_data/azure/maps.json")
If (success <> True) Then
System.DebugLog("Could not load private Azure Maps configuration.")
Return
End If
If (config.JsonTypeOf("subscription_key") <> 1) Then
System.DebugLog("Missing or invalid subscription_key.")
Return
End If
If (config.StringOfEquals("subscription_key","",True) = True) Then
System.DebugLog("A nonempty subscription_key is required.")
Return
End If
Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 30
http.ReadTimeout = 90
http.Accept = "application/json"
Dim response As New Chilkat.HttpResponse
Dim result As New Chilkat.JsonObject
result.Strict = True
Dim query As New 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.
Dim resumeOperation As Boolean
resumeOperation = False
Dim job As New Chilkat.JsonObject
job.Strict = True
Dim operationUrl As String
If (resumeOperation = True) Then
success = job.LoadFile("azure-maps-matrix-operation.json")
If (success <> True) Then
System.DebugLog("Could not load saved matrix operation.")
Return
End If
If (job.JsonTypeOf("operation_url") <> 1) Then
System.DebugLog("Missing or invalid operation_url.")
Return
End If
If (job.StringOfEquals("operation_url","",True) = True) Then
System.DebugLog("A nonempty operation_url is required.")
Return
End If
operationUrl = job.StringOf("operation_url")
Else
Dim body As New 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
System.DebugLog("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
Return
End If
If (response.StatusCode <> 202) Then
System.DebugLog("HTTP status: " + Str(response.StatusCode))
System.DebugLog("Error code: " + response.GetHeaderField("x-ms-error-code"))
System.DebugLog("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
End If
If (success <> True) Then
System.DebugLog("The HTTP response was incomplete.")
Return
End If
operationUrl = response.GetHeaderField("Operation-Location")
End If
// Validate the polling destination before sending the account key to it.
Dim parsed As New Chilkat.Url
success = parsed.ParseUrl(operationUrl)
If (success <> True) Then
System.DebugLog("Missing or invalid Operation-Location.")
Return
End If
success = stringCompare.SetString(parsed.Scheme)
Dim stringMatch1 As Boolean
stringMatch1 = stringCompare.ContentsEqual("https",True)
success = stringCompare.SetString(parsed.Host)
Dim stringMatch2 As Boolean
stringMatch2 = stringCompare.ContentsEqual("atlas.microsoft.com",True)
success = stringCompare.SetString(parsed.Login)
Dim stringMatch3 As Boolean
stringMatch3 = stringCompare.ContentsEqual("",True)
success = stringCompare.SetString(parsed.Password)
Dim stringMatch4 As Boolean
stringMatch4 = stringCompare.ContentsEqual("",True)
success = stringCompare.SetString(parsed.Frag)
Dim stringMatch5 As Boolean
stringMatch5 = stringCompare.ContentsEqual("",True)
If ((stringMatch1 <> True) Or (stringMatch2 <> True) Or (parsed.Port <> 443) Or (stringMatch3 <> True) Or (stringMatch4 <> True) Or (stringMatch5 <> True)) Then
System.DebugLog("Unexpected operation URL; refusing to send credentials.")
Return
End If
Dim pathText As New Chilkat.StringBuilder
success = pathText.Append(parsed.Path)
If (pathText.StartsWith("/route/operations/",True) <> True) Then
System.DebugLog("Unexpected operation path.")
Return
End If
Dim operationId As String
operationId = pathText.GetAfterFinal("/",False)
success = stringCompare.SetString(operationId)
Dim stringMatch6 As Boolean
stringMatch6 = stringCompare.ContentsEqual("",True)
If (stringMatch6 = True) Then
System.DebugLog("Missing operation ID.")
Return
End If
// Treat the ID as text. Rebuild URLs on the fixed Maps host.
success = http.SetUrlVar("operationId",operationId)
If (success <> True) Then
System.DebugLog("Could not encode operation ID.")
Return
End If
success = job.UpdateString("operation_url",operationUrl)
success = job.WriteFile("azure-maps-matrix-operation.json")
If (success <> True) Then
System.DebugLog("Could not save the operation for resuming.")
Return
End If
System.DebugLog("Saved matrix operation. Set resumeOperation to true to resume it.")
If (resumeOperation <> True) Then
Dim submitRetryAfter As String
submitRetryAfter = response.GetHeaderField("Retry-After")
success = stringCompare.SetString(submitRetryAfter)
Dim stringMatch7 As Boolean
stringMatch7 = stringCompare.ContentsEqual("",True)
If (stringMatch7 <> True) Then
System.DebugLog("Resume after Retry-After: " + submitRetryAfter)
Return
End If
End If
// Do not resubmit a POST automatically after a transport failure: the job may exist.
Dim attempt As Int32
attempt = 0
Dim complete As Boolean
complete = False
While ((attempt < 30) And (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.StatusCode = 0) Then
System.DebugLog("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
Return
End If
If (response.StatusCode <> 200) Then
System.DebugLog("HTTP status: " + Str(response.StatusCode))
System.DebugLog("Error code: " + response.GetHeaderField("x-ms-error-code"))
System.DebugLog("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
End If
If (success <> True) Then
System.DebugLog("The HTTP response was incomplete.")
Return
End If
success = result.Load(response.BodyStr)
If (success <> True) Then
System.DebugLog("Expected a well-formed JSON response.")
Return
End If
If (result.StringOfEquals("status","Completed",True) = True) Then
complete = True
Else
If (result.StringOfEquals("status","Failed",True) = True) Then
System.DebugLog("Matrix operation failed: " + result.StringOf("error.code"))
Return
End If
If ((result.StringOfEquals("status","Running",True) <> True) And (result.StringOfEquals("status","NotStarted",True) <> True)) Then
System.DebugLog("Unexpected operation status.")
Return
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.
Dim retryAfter As String
retryAfter = response.GetHeaderField("Retry-After")
success = stringCompare.SetString(retryAfter)
Dim stringMatch8 As Boolean
stringMatch8 = stringCompare.ContentsEqual("",True)
If (stringMatch8 <> True) Then
System.DebugLog("Resume after Retry-After: " + retryAfter)
Return
End If
End If
attempt = attempt + 1
Wend
If (complete <> True) Then
System.DebugLog("Polling limit reached; resume the saved operation later.")
Return
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
System.DebugLog("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
Return
End If
If (response.StatusCode <> 200) Then
System.DebugLog("HTTP status: " + Str(response.StatusCode))
System.DebugLog("Error code: " + response.GetHeaderField("x-ms-error-code"))
System.DebugLog("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
End If
If (success <> True) Then
System.DebugLog("The HTTP response was incomplete.")
Return
End If
success = result.Load(response.BodyStr)
If (success <> True) Then
System.DebugLog("Expected a well-formed JSON response.")
Return
End If
Dim matrix As New Chilkat.JsonArray
Dim cell As New Chilkat.JsonObject
success = result.ArrayOf2("properties.matrix",matrix)
If (success <> True) Then
System.DebugLog("Expected a matrix array.")
Return
End If
If (matrix.Size <> 4) Then
System.DebugLog("Expected four origin/destination results for this 2-by-2 request.")
Return
End If
Dim i As Int32
i = 0
While (i < matrix.Size)
success = matrix.ObjectAt2(i,cell)
If (success <> True) Then
System.DebugLog("Invalid matrix entry.")
Return
End If
If (cell.JsonTypeOf("originIndex") <> 2) Then
System.DebugLog("Missing or invalid originIndex.")
Return
End If
If (cell.JsonTypeOf("destinationIndex") <> 2) Then
System.DebugLog("Missing or invalid destinationIndex.")
Return
End If
If (cell.JsonTypeOf("statusCode") <> 2) Then
System.DebugLog("Missing or invalid statusCode.")
Return
End If
// Use the explicit indexes; do not assume matrix entry order.
System.DebugLog("Origin index: " + Str(cell.IntOf("originIndex")))
System.DebugLog("Destination index: " + Str(cell.IntOf("destinationIndex")))
If (cell.IntOf("statusCode") = 200) Then
If (cell.JsonTypeOf("distanceInMeters") <> 2) Then
System.DebugLog("Missing or invalid distanceInMeters.")
Return
End If
If (cell.JsonTypeOf("durationInSeconds") <> 2) Then
System.DebugLog("Missing or invalid durationInSeconds.")
Return
End If
System.DebugLog("Distance (meters): " + cell.StringOf("distanceInMeters"))
System.DebugLog("Duration (seconds): " + cell.StringOf("durationInSeconds"))
Else
System.DebugLog("Route error: " + cell.StringOf("error.code"))
End If
i = i + 1
Wend
success = result.WriteFile("azure-maps-matrix.json")
If (success <> True) Then
System.DebugLog("Could not save matrix result.")
Return
End If
System.DebugLog("Saved azure-maps-matrix.json")