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 B4X Downloads
Dim success As Boolean = False
Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
' This example requires the Chilkat API to have been previously unlocked.
' See Global.UnlockBundle for sample code.
Dim config As ChilkatJsonObject
config.Initialize
config.Strict = True
' Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success = config.LoadFile("qa_data/azure/maps.json")
If success <> True Then
Log("Could not load private Azure Maps configuration.")
Return
End If
If config.JsonTypeOf("subscription_key") <> 1 Then
Log("Missing or invalid subscription_key.")
Return
End If
If config.StringOfEquals("subscription_key", "", True) = True Then
Log("A nonempty subscription_key is required.")
Return
End If
Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 30
http.ReadTimeout = 90
http.Accept = "application/json"
Dim response As ChilkatHttpResponse
response.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim query As ChilkatJsonObject
query.Initialize
' 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 = False
Dim job As ChilkatJsonObject
job.Initialize
job.Strict = True
Dim operationUrl As String
If resumeOperation = True Then
success = job.LoadFile("azure-maps-matrix-operation.json")
If success <> True Then
Log("Could not load saved matrix operation.")
Return
End If
If job.JsonTypeOf("operation_url") <> 1 Then
Log("Missing or invalid operation_url.")
Return
End If
If job.StringOfEquals("operation_url", "", True) = True Then
Log("A nonempty operation_url is required.")
Return
End If
operationUrl = job.StringOf("operation_url")
Else
Dim body As ChilkatJsonObject
body.Initialize
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, "application/geo+json", response)
' Http methods return false for HTTP errors as well as transport failures.
If response.StatusCode = 0 Then
Log("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
Return
End If
If response.StatusCode <> 202 Then
Log("HTTP status: " & response.StatusCode)
Log("Error code: " & response.GetHeaderField("x-ms-error-code"))
Log("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
Log("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 ChilkatUrl
parsed.Initialize
success = parsed.ParseUrl(operationUrl)
If success <> True Then
Log("Missing or invalid Operation-Location.")
Return
End If
stringCompare.SetString(parsed.Scheme)
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("https", True)
stringCompare.SetString(parsed.Host)
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("atlas.microsoft.com", True)
stringCompare.SetString(parsed.Login)
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
stringCompare.SetString(parsed.Password)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
stringCompare.SetString(parsed.Frag)
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (stringMatch1 <> True) Or (stringMatch2 <> True) Or (parsed.Port <> 443) Or (stringMatch3 <> True) Or (stringMatch4 <> True) Or (stringMatch5 <> True) Then
Log("Unexpected operation URL; refusing to send credentials.")
Return
End If
Dim pathText As ChilkatStringBuilder
pathText.Initialize
pathText.Append(parsed.Path)
If pathText.StartsWith("/route/operations/", True) <> True Then
Log("Unexpected operation path.")
Return
End If
Dim operationId As String = pathText.GetAfterFinal("/", False)
stringCompare.SetString(operationId)
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch6 = True Then
Log("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
Log("Could not encode operation ID.")
Return
End If
job.UpdateString("operation_url", operationUrl)
success = job.WriteFile("azure-maps-matrix-operation.json")
If success <> True Then
Log("Could not save the operation for resuming.")
Return
End If
Log("Saved matrix operation. Set resumeOperation to true to resume it.")
If resumeOperation <> True Then
Dim submitRetryAfter As String = response.GetHeaderField("Retry-After")
stringCompare.SetString(submitRetryAfter)
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch7 <> True Then
Log("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 Int = 0
Dim complete As Boolean = False
Do 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
Log("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
Return
End If
If response.StatusCode <> 200 Then
Log("HTTP status: " & response.StatusCode)
Log("Error code: " & response.GetHeaderField("x-ms-error-code"))
Log("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
Log("The HTTP response was incomplete.")
Return
End If
success = result.Load(response.BodyStr)
If success <> True Then
Log("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
Log("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
Log("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 = response.GetHeaderField("Retry-After")
stringCompare.SetString(retryAfter)
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch8 <> True Then
Log("Resume after Retry-After: " & retryAfter)
Return
End If
End If
attempt = attempt + 1
Loop
If complete <> True Then
Log("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
Log("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
Return
End If
If response.StatusCode <> 200 Then
Log("HTTP status: " & response.StatusCode)
Log("Error code: " & response.GetHeaderField("x-ms-error-code"))
Log("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
Log("The HTTP response was incomplete.")
Return
End If
success = result.Load(response.BodyStr)
If success <> True Then
Log("Expected a well-formed JSON response.")
Return
End If
Dim matrix As ChilkatJsonArray
matrix.Initialize
Dim cell As ChilkatJsonObject
cell.Initialize
success = result.ArrayOf2("properties.matrix", matrix)
If success <> True Then
Log("Expected a matrix array.")
Return
End If
If matrix.Size <> 4 Then
Log("Expected four origin/destination results for this 2-by-2 request.")
Return
End If
Dim i As Int = 0
Do While (i < matrix.Size)
success = matrix.ObjectAt2(i, cell)
If success <> True Then
Log("Invalid matrix entry.")
Return
End If
If cell.JsonTypeOf("originIndex") <> 2 Then
Log("Missing or invalid originIndex.")
Return
End If
If cell.JsonTypeOf("destinationIndex") <> 2 Then
Log("Missing or invalid destinationIndex.")
Return
End If
If cell.JsonTypeOf("statusCode") <> 2 Then
Log("Missing or invalid statusCode.")
Return
End If
' Use the explicit indexes; do not assume matrix entry order.
Log("Origin index: " & cell.IntOf("originIndex"))
Log("Destination index: " & cell.IntOf("destinationIndex"))
If cell.IntOf("statusCode") = 200 Then
If cell.JsonTypeOf("distanceInMeters") <> 2 Then
Log("Missing or invalid distanceInMeters.")
Return
End If
If cell.JsonTypeOf("durationInSeconds") <> 2 Then
Log("Missing or invalid durationInSeconds.")
Return
End If
Log("Distance (meters): " & cell.StringOf("distanceInMeters"))
Log("Duration (seconds): " & cell.StringOf("durationInSeconds"))
Else
Log("Route error: " & cell.StringOf("error.code"))
End If
i = i + 1
Loop
success = result.WriteFile("azure-maps-matrix.json")
If success <> True Then
Log("Could not save matrix result.")
Return
End If
Log("Saved azure-maps-matrix.json")