Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

Azure Maps: Calculate Route Directions

See more Azure Maps Examples

Posts origin and destination waypoints to Route 2025-01-01. Requests both route geometry and itinerary, and reads each response feature according to its properties.type. Prints distance, duration without traffic, and plain-text maneuver instructions; saves the complete response as GeoJSON.

The example selects driving and fastest-without-traffic optimization. Use a suitable travel mode and route options for your application. GeoJSON points use longitude first. The output file in the current directory replaces any same-named file.

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

#  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"))
#  Route 2025 takes GeoJSON in a POST body, with longitude first.
body = Chilkat::CkJsonObject.new()
body.UpdateString("type","FeatureCollection")
body.UpdateString("features[0].type","Feature")
body.UpdateString("features[0].geometry.type","Point")
body.UpdateNumber("features[0].geometry.coordinates[0]","-122.201399")
body.UpdateNumber("features[0].geometry.coordinates[1]","47.608678")
body.UpdateString("features[0].properties.pointType","waypoint")
body.UpdateInt("features[0].properties.pointIndex",0)
body.UpdateString("features[1].type","Feature")
body.UpdateString("features[1].geometry.type","Point")
body.UpdateNumber("features[1].geometry.coordinates[0]","-122.201669")
body.UpdateNumber("features[1].geometry.coordinates[1]","47.615076")
body.UpdateString("features[1].properties.pointType","waypoint")
body.UpdateInt("features[1].properties.pointIndex",1)
body.UpdateString("travelMode","driving")
body.UpdateInt("maxRouteCount",1)
body.UpdateString("optimizeRoute","fastestWithoutTraffic")
body.UpdateString("routeOutputOptions[0]","routePath")
body.UpdateString("routeOutputOptions[1]","itinerary")
success = http.HttpJson("POST","https://atlas.microsoft.com/route/directions?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() != 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

features = Chilkat::CkJsonArray.new()
feature = Chilkat::CkJsonObject.new()
if (result.StringOfEquals("type","FeatureCollection",true) != true)
    print "Expected a GeoJSON FeatureCollection." + "\n";
    exit
end

success = result.ArrayOf2("features",features)
if (success != true)
    print "Expected a features array." + "\n";
    exit
end

i = 0
foundRoute = false
while (i < features.get_Size())
    success = features.ObjectAt2(i,feature)
    if (success != true)
        print "Invalid route feature." + "\n";
        exit
    end

    if (feature.StringOfEquals("properties.type","RoutePath",true) == true)
        if (feature.JsonTypeOf("properties.distanceInMeters") != 2)
            print "Missing or invalid properties.distanceInMeters." + "\n";
            exit
        end

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

        foundRoute = true
        print "Distance (meters): " + feature.stringOf("properties.distanceInMeters") + "\n";
        print "Duration without traffic (seconds): " + feature.stringOf("properties.durationInSeconds") + "\n";
    end

    if (feature.StringOfEquals("properties.type","ManeuverPoint",true) == true)
        #  Use plain text rather than rendering formattedText as untrusted HTML.
        print "Instruction: " + feature.stringOf("properties.instruction.text") + "\n";
    end

    i = i + 1
end
if (foundRoute != true)
    print "No RoutePath feature was returned." + "\n";
    exit
end

success = result.WriteFile("azure-maps-route.geojson")
if (success != true)
    print "Could not save the route." + "\n";
    exit
end

print "Saved azure-maps-route.geojson" + "\n";