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

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.new()
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global.UnlockBundle for sample code.

local config = chilkat.JsonObject.new()
config.strict = true
-- Private file: {"subscription_key":"YOUR_AZURE_MAPS_KEY"}.
local success = config:load_file("qa_data/azure/maps.json")
if not success then
    print("Could not load private Azure Maps configuration.")
    return
end

if config:json_type_of("subscription_key") ~= 1 then
    print("Missing or invalid subscription_key.")
    return
end

if config:string_of_equals("subscription_key", "", true) then
    print("A nonempty subscription_key is required.")
    return
end

local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 30
http.read_timeout = 90
http.accept = "application/json"
local response = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
local query = chilkat.JsonObject.new()
-- Current Azure Maps operations accept the key as a header.
http:set_request_header("subscription-key", config:string_of("subscription_key"))
-- Set true to resume the saved operation instead of submitting another job.
local resumeOperation = false
local job = chilkat.JsonObject.new()
job.strict = true
local operationUrl = ""
if resumeOperation then
    success = job:load_file("azure-maps-matrix-operation.json")
    if not success then
        print("Could not load saved matrix operation.")
        return
    end

    if job:json_type_of("operation_url") ~= 1 then
        print("Missing or invalid operation_url.")
        return
    end

    if job:string_of_equals("operation_url", "", true) then
        print("A nonempty operation_url is required.")
        return
    end

    operationUrl = job:string_of("operation_url")
else
    local body = chilkat.JsonObject.new()
    body:update_string("type", "FeatureCollection")
    body:update_string("features[0].type", "Feature")
    body:update_string("features[0].geometry.type", "MultiPoint")
    body:update_number("features[0].geometry.coordinates[0][0]", "-122.201399")
    body:update_number("features[0].geometry.coordinates[0][1]", "47.608678")
    body:update_number("features[0].geometry.coordinates[1][0]", "-122.136833")
    body:update_number("features[0].geometry.coordinates[1][1]", "47.642282")
    body:update_string("features[0].properties.pointType", "origins")
    body:update_string("features[1].type", "Feature")
    body:update_string("features[1].geometry.type", "MultiPoint")
    body:update_number("features[1].geometry.coordinates[0][0]", "-122.201669")
    body:update_number("features[1].geometry.coordinates[0][1]", "47.615076")
    body:update_number("features[1].geometry.coordinates[1][0]", "-122.341979")
    body:update_number("features[1].geometry.coordinates[1][1]", "47.609525")
    body:update_string("features[1].properties.pointType", "destinations")
    body:update_string("travelMode", "driving")
    body:update_string("optimizeRoute", "fastest")
    body:update_string("traffic", "historical")
    success = http:http_json("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.status_code == 0 then
        print("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
        return
    end

    if response.status_code ~= 202 then
        print("HTTP status: " .. response.status_code)
        print("Error code: " .. response:get_header_field("x-ms-error-code"))
        print("Retry-After: " .. response:get_header_field("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 not success then
        print("The HTTP response was incomplete.")
        return
    end

    operationUrl = response:get_header_field("Operation-Location")
end

-- Validate the polling destination before sending the account key to it.
local parsed = chilkat.Url.new()
success = parsed:parse_url(operationUrl)
if not success then
    print("Missing or invalid Operation-Location.")
    return
end

stringCompare:set_string(parsed.scheme)
local stringMatch1 = stringCompare:contents_equal("https", true)
stringCompare:set_string(parsed.host)
local stringMatch2 = stringCompare:contents_equal("atlas.microsoft.com", true)
stringCompare:set_string(parsed.login)
local stringMatch3 = stringCompare:contents_equal("", true)
stringCompare:set_string(parsed.password)
local stringMatch4 = stringCompare:contents_equal("", true)
stringCompare:set_string(parsed.frag)
local stringMatch5 = stringCompare:contents_equal("", true)
if (not stringMatch1) or ((not stringMatch2) or ((parsed.port ~= 443) or ((not stringMatch3) or ((not stringMatch4) or (not stringMatch5))))) then
    print("Unexpected operation URL; refusing to send credentials.")
    return
end

local pathText = chilkat.StringBuilder.new()
pathText:append(parsed.path)
if not pathText:starts_with("/route/operations/", true) then
    print("Unexpected operation path.")
    return
end

local operationId = pathText:get_after_final("/", false)
stringCompare:set_string(operationId)
local stringMatch6 = stringCompare:contents_equal("", true)
if stringMatch6 then
    print("Missing operation ID.")
    return
end

-- Treat the ID as text. Rebuild URLs on the fixed Maps host.
success = http:set_url_var("operationId", operationId)
if not success then
    print("Could not encode operation ID.")
    return
end

job:update_string("operation_url", operationUrl)
success = job:write_file("azure-maps-matrix-operation.json")
if not success then
    print("Could not save the operation for resuming.")
    return
end

print("Saved matrix operation. Set resumeOperation to true to resume it.")
if not resumeOperation then
    local submitRetryAfter = response:get_header_field("Retry-After")
    stringCompare:set_string(submitRetryAfter)
    local stringMatch7 = stringCompare:contents_equal("", true)
    if not stringMatch7 then
        print("Resume after Retry-After: " .. submitRetryAfter)
        return
    end
end

-- Do not resubmit a POST automatically after a transport failure: the job may exist.
local attempt = 0
local complete = false
while (attempt < 30) and (not complete) do
    -- A short example limit. A production worker should schedule polling off the UI thread.
    http:sleep_ms(2000)
    success = http:http_no_body("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.status_code == 0 then
        print("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
        return
    end

    if response.status_code ~= 200 then
        print("HTTP status: " .. response.status_code)
        print("Error code: " .. response:get_header_field("x-ms-error-code"))
        print("Retry-After: " .. response:get_header_field("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 not success then
        print("The HTTP response was incomplete.")
        return
    end

    success = result:load(response.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

    if result:string_of_equals("status", "Completed", true) then
        complete = true
    else
        if result:string_of_equals("status", "Failed", true) then
            print("Matrix operation failed: " .. result:string_of("error.code"))
            return
        end

        if (not result:string_of_equals("status", "Running", true)) and (not result:string_of_equals("status", "NotStarted", true)) then
            print("Unexpected operation status.")
            return
        end

        -- If the service supplies Retry-After, defer to the caller's scheduler.
        -- Preserve the job and resume no sooner than that header permits.
        local retryAfter = response:get_header_field("Retry-After")
        stringCompare:set_string(retryAfter)
        local stringMatch8 = stringCompare:contents_equal("", true)
        if not stringMatch8 then
            print("Resume after Retry-After: " .. retryAfter)
            return
        end
    end

    attempt = attempt + 1
end

if not complete then
    print("Polling limit reached; resume the saved operation later.")
    return
end

-- Use the documented result endpoint on the same fixed host.
success = http:http_no_body("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.status_code == 0 then
    print("No HTTP response. Inspect diagnostics privately; they can contain credentials.")
    return
end

if response.status_code ~= 200 then
    print("HTTP status: " .. response.status_code)
    print("Error code: " .. response:get_header_field("x-ms-error-code"))
    print("Retry-After: " .. response:get_header_field("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 not success then
    print("The HTTP response was incomplete.")
    return
end

success = result:load(response.body_str)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

local matrix = chilkat.JsonArray.new()
local cell = chilkat.JsonObject.new()
success = result:array_of2("properties.matrix", matrix)
if not success then
    print("Expected a matrix array.")
    return
end

if matrix.size ~= 4 then
    print("Expected four origin/destination results for this 2-by-2 request.")
    return
end

local i = 0
while i < matrix.size do
    success = matrix:object_at2(i, cell)
    if not success then
        print("Invalid matrix entry.")
        return
    end

    if cell:json_type_of("originIndex") ~= 2 then
        print("Missing or invalid originIndex.")
        return
    end

    if cell:json_type_of("destinationIndex") ~= 2 then
        print("Missing or invalid destinationIndex.")
        return
    end

    if cell:json_type_of("statusCode") ~= 2 then
        print("Missing or invalid statusCode.")
        return
    end

    -- Use the explicit indexes; do not assume matrix entry order.
    print("Origin index: " .. cell:int_of("originIndex"))
    print("Destination index: " .. cell:int_of("destinationIndex"))
    if cell:int_of("statusCode") == 200 then
        if cell:json_type_of("distanceInMeters") ~= 2 then
            print("Missing or invalid distanceInMeters.")
            return
        end

        if cell:json_type_of("durationInSeconds") ~= 2 then
            print("Missing or invalid durationInSeconds.")
            return
        end

        print("Distance (meters): " .. cell:string_of("distanceInMeters"))
        print("Duration (seconds): " .. cell:string_of("durationInSeconds"))
    else
        print("Route error: " .. cell:string_of("error.code"))
    end

    i = i + 1
end

success = result:write_file("azure-maps-matrix.json")
if not success then
    print("Could not save matrix result.")
    return
end

print("Saved azure-maps-matrix.json")