Geocode an address with Thinwrap (Gleam)

Resolve an address to coordinates via thinwrap_location's geocode/2 in Gleam — one call shape for Mapbox, Google, HERE and more.

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", "geocode")
fn geocode(config: Dynamic, input: Dynamic) -> Result(Dynamic, Dynamic)

pub fn main() -> Nil {
  let assert Ok(api_key) = envoy.get("GOOGLE_MAPS_API_KEY")
  let config =
    obj([#("provider", atom("google")), #("api_key", dynamic.string(api_key))])
  let input =
    obj([
      #(
        "address",
        dynamic.string("1600 Amphitheatre Parkway, Mountain View, CA"),
      ),
      #("country_filter", dynamic.list([dynamic.string("US")])),
    ])

  case geocode(config, input) {
    Ok(res) -> {
      let candidate = {
        use address <- decode.field(key("formatted_address"), decode.string)
        use lat <- decode.subfield([key("location"), key("lat")], decode.float)
        use lng <- decode.subfield([key("location"), key("lng")], decode.float)
        decode.success(
          address <> " " <> float.to_string(lat) <> " " <> float.to_string(lng),
        )
      }
      let assert Ok(lines) =
        decode.run(res, decode.at([key("candidates")], decode.list(candidate)))
      list.each(lines, io.println)
    }
    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 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.