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

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  This example requires the Chilkat API to have been previously unlocked.
#  See Global.UnlockBundle for sample code.

config = Chilkat::CkJsonObject.new()
config.put_Strict(true)
#  Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
success = config.LoadFile("qa_data/azure/maps.json")
if (success != true)
    print "Could not load private Azure Maps configuration." + "\n";
    exit
end

if (config.JsonTypeOf("subscription_key") != 1)
    print "Missing or invalid subscription_key." + "\n";
    exit
end

if (config.StringOfEquals("subscription_key","",true) == true)
    print "A nonempty subscription_key is required." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(30)
http.put_ReadTimeout(90)
http.put_Accept("application/json")
response = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
query = Chilkat::CkJsonObject.new()
#  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 = false
job = Chilkat::CkJsonObject.new()
job.put_Strict(true)

if (resumeOperation == true)
    success = job.LoadFile("azure-maps-matrix-operation.json")
    if (success != true)
        print "Could not load saved matrix operation." + "\n";
        exit
    end

    if (job.JsonTypeOf("operation_url") != 1)
        print "Missing or invalid operation_url." + "\n";
        exit
    end

    if (job.StringOfEquals("operation_url","",true) == true)
        print "A nonempty operation_url is required." + "\n";
        exit
    end

    operationUrl = job.stringOf("operation_url")
else
    body = Chilkat::CkJsonObject.new()
    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.get_StatusCode() == 0)
        print "No HTTP response. Inspect diagnostics privately; they can contain credentials." + "\n";
        exit
    end

    if (response.get_StatusCode() != 202)
        print "HTTP status: " + response.get_StatusCode().to_s() + "\n";
        print "Error code: " + response.getHeaderField("x-ms-error-code") + "\n";
        print "Retry-After: " + response.getHeaderField("Retry-After") + "\n";
        #  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
    end

    if (success != true)
        print "The HTTP response was incomplete." + "\n";
        exit
    end

    operationUrl = response.getHeaderField("Operation-Location")
end

#  Validate the polling destination before sending the account key to it.
parsed = Chilkat::CkUrl.new()
success = parsed.ParseUrl(operationUrl)
if (success != true)
    print "Missing or invalid Operation-Location." + "\n";
    exit
end

stringCompare.SetString(parsed.scheme())
stringMatch1 = stringCompare.ContentsEqual("https",true)
stringCompare.SetString(parsed.host())
stringMatch2 = stringCompare.ContentsEqual("atlas.microsoft.com",true)
stringCompare.SetString(parsed.login())
stringMatch3 = stringCompare.ContentsEqual("",true)
stringCompare.SetString(parsed.password())
stringMatch4 = stringCompare.ContentsEqual("",true)
stringCompare.SetString(parsed.frag())
stringMatch5 = stringCompare.ContentsEqual("",true)
if ((stringMatch1 != true) or (stringMatch2 != true) or (parsed.get_Port() != 443) or (stringMatch3 != true) or (stringMatch4 != true) or (stringMatch5 != true))
    print "Unexpected operation URL; refusing to send credentials." + "\n";
    exit
end

pathText = Chilkat::CkStringBuilder.new()
pathText.Append(parsed.path())
if (pathText.StartsWith("/route/operations/",true) != true)
    print "Unexpected operation path." + "\n";
    exit
end

operationId = pathText.getAfterFinal("/",false)
stringCompare.SetString(operationId)
stringMatch6 = stringCompare.ContentsEqual("",true)
if (stringMatch6 == true)
    print "Missing operation ID." + "\n";
    exit
end

#  Treat the ID as text. Rebuild URLs on the fixed Maps host.
success = http.SetUrlVar("operationId",operationId)
if (success != true)
    print "Could not encode operation ID." + "\n";
    exit
end

job.UpdateString("operation_url",operationUrl)
success = job.WriteFile("azure-maps-matrix-operation.json")
if (success != true)
    print "Could not save the operation for resuming." + "\n";
    exit
end

print "Saved matrix operation. Set resumeOperation to true to resume it." + "\n";
if (resumeOperation != true)
    submitRetryAfter = response.getHeaderField("Retry-After")
    stringCompare.SetString(submitRetryAfter)
    stringMatch7 = stringCompare.ContentsEqual("",true)
    if (stringMatch7 != true)
        print "Resume after Retry-After: " + submitRetryAfter + "\n";
        exit
    end

end

#  Do not resubmit a POST automatically after a transport failure: the job may exist.
attempt = 0
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.get_StatusCode() == 0)
        print "No HTTP response. Inspect diagnostics privately; they can contain credentials." + "\n";
        exit
    end

    if (response.get_StatusCode() != 200)
        print "HTTP status: " + response.get_StatusCode().to_s() + "\n";
        print "Error code: " + response.getHeaderField("x-ms-error-code") + "\n";
        print "Retry-After: " + response.getHeaderField("Retry-After") + "\n";
        #  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
    end

    if (success != true)
        print "The HTTP response was incomplete." + "\n";
        exit
    end

    success = result.Load(response.bodyStr())
    if (success != true)
        print "Expected a well-formed JSON response." + "\n";
        exit
    end

    if (result.StringOfEquals("status","Completed",true) == true)
        complete = true
    else
        if (result.StringOfEquals("status","Failed",true) == true)
            print "Matrix operation failed: " + result.stringOf("error.code") + "\n";
            exit
        end

        if ((result.StringOfEquals("status","Running",true) != true) and (result.StringOfEquals("status","NotStarted",true) != true))
            print "Unexpected operation status." + "\n";
            exit
        end

        #  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")
        stringCompare.SetString(retryAfter)
        stringMatch8 = stringCompare.ContentsEqual("",true)
        if (stringMatch8 != true)
            print "Resume after Retry-After: " + retryAfter + "\n";
            exit
        end

    end

    attempt = attempt + 1
end
if (complete != true)
    print "Polling limit reached; resume the saved operation later." + "\n";
    exit
end

#  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.get_StatusCode() == 0)
    print "No HTTP response. Inspect diagnostics privately; they can contain credentials." + "\n";
    exit
end

if (response.get_StatusCode() != 200)
    print "HTTP status: " + response.get_StatusCode().to_s() + "\n";
    print "Error code: " + response.getHeaderField("x-ms-error-code") + "\n";
    print "Retry-After: " + response.getHeaderField("Retry-After") + "\n";
    #  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
end

if (success != true)
    print "The HTTP response was incomplete." + "\n";
    exit
end

success = result.Load(response.bodyStr())
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

matrix = Chilkat::CkJsonArray.new()
cell = Chilkat::CkJsonObject.new()
success = result.ArrayOf2("properties.matrix",matrix)
if (success != true)
    print "Expected a matrix array." + "\n";
    exit
end

if (matrix.get_Size() != 4)
    print "Expected four origin/destination results for this 2-by-2 request." + "\n";
    exit
end

i = 0
while (i < matrix.get_Size())
    success = matrix.ObjectAt2(i,cell)
    if (success != true)
        print "Invalid matrix entry." + "\n";
        exit
    end

    if (cell.JsonTypeOf("originIndex") != 2)
        print "Missing or invalid originIndex." + "\n";
        exit
    end

    if (cell.JsonTypeOf("destinationIndex") != 2)
        print "Missing or invalid destinationIndex." + "\n";
        exit
    end

    if (cell.JsonTypeOf("statusCode") != 2)
        print "Missing or invalid statusCode." + "\n";
        exit
    end

    #  Use the explicit indexes; do not assume matrix entry order.
    print "Origin index: " + cell.IntOf("originIndex").to_s() + "\n";
    print "Destination index: " + cell.IntOf("destinationIndex").to_s() + "\n";
    if (cell.IntOf("statusCode") == 200)
        if (cell.JsonTypeOf("distanceInMeters") != 2)
            print "Missing or invalid distanceInMeters." + "\n";
            exit
        end

        if (cell.JsonTypeOf("durationInSeconds") != 2)
            print "Missing or invalid durationInSeconds." + "\n";
            exit
        end

        print "Distance (meters): " + cell.stringOf("distanceInMeters") + "\n";
        print "Duration (seconds): " + cell.stringOf("durationInSeconds") + "\n";
    else
        print "Route error: " + cell.stringOf("error.code") + "\n";
    end

    i = i + 1
end
success = result.WriteFile("azure-maps-matrix.json")
if (success != true)
    print "Could not save matrix result." + "\n";
    exit
end

print "Saved azure-maps-matrix.json" + "\n";