Compute a route with Thinwrap (Gleam)

Compute a route via thinwrap_location's route/2 in Gleam — one call shape for Mapbox, Google, HERE, ESRI, TomTom and OSRM.

1. Install

gleam add thinwrap_location gleam_erlang envoy

2. Send the call

import envoy
import gleam/dynamic.{type Dynamic}
import gleam/dynamic/decode
import gleam/erlang/atom
import gleam/float
import gleam/io
import gleam/list

@external(erlang, "thinwrap_location", "route")
fn route(config: Dynamic, input: Dynamic) -> Result(Dynamic, Dynamic)

pub fn main() -> Nil {
  let assert Ok(token) = envoy.get("MAPBOX_ACCESS_TOKEN")
  let config =
    obj([
      #("provider", atom("mapbox")),
      #("access_token", dynamic.string(token)),
    ])
  let input =
    obj([
      #("waypoints", dynamic.list([at(52.52, 13.405), at(52.5163, 13.3777)])),
      #("travel_mode", atom("driving")),
    ])

  case route(config, input) {
    // polyline is the encoded geometry; raw keeps the vendor body verbatim.
    Ok(res) -> {
      let totals = {
        use meters <- decode.field(key("total_distance_meters"), decode.float)
        use seconds <- decode.field(key("total_duration_seconds"), decode.float)
        decode.success(
          float.to_string(meters) <> " " <> float.to_string(seconds),
        )
      }
      let assert Ok(line) = decode.run(res, totals)
      io.println(line)
    }
    Error(err) -> io.println(describe(err))
  }
}

// The library speaks atom-keyed Erlang maps; these helpers build and read them.
fn key(name: String) -> atom.Atom {
  atom.create(name)
}

fn atom(name: String) -> Dynamic {
  atom.to_dynamic(atom.create(name))
}

fn obj(fields: List(#(String, Dynamic))) -> Dynamic {
  dynamic.properties(list.map(fields, fn(f) { #(atom(f.0), f.1) }))
}

fn at(lat: Float, lng: Float) -> Dynamic {
  obj([#("lat", dynamic.float(lat)), #("lng", dynamic.float(lng))])
}

fn describe(err: Dynamic) -> String {
  let error = {
    use code <- decode.field(key("code"), atom.decoder())
    use message <- decode.field(key("message"), decode.string)
    decode.success(atom.to_string(code) <> ": " <> message)
  }
  let assert Ok(line) = decode.run(err, error)
  line
}

Same code works for all supported providers — just change the provider ID.