Rust Geocoding Tutorial

This is a tutorial for using the OpenCage geocoding API in Rust.

Topics covered in this tutorial


The code examples below will use your geocoding API key once you log in.

Before we dive in to the tutorial

  1. Sign up for an OpenCage geocoding API key.
  2. Play with the demo page, so that you see the actual response the API returns.
  3. Browse the API reference, so you understand the optional parameters, best practices, possible response codes, and the rate limiting on free trial accounts.

Rust library for forward and reverse geocoding

Tested with Rust 1.3. The library doesn't have command-line binaries so cargo install geocoding won't work.

Create a new project cargo init and/or add this to your existing Cargo.toml file:

geocoding = "0.4.0"

Coordinates to address (reverse geocoding)

use geocoding::{Opencage, Reverse, Point};

fn main() {
  let p = Point::new(2.12870, 41.40139);
  let oc = Opencage::new("YOUR-API-KEY".to_string());
  let res = oc.reverse(&p);

  println!("{:?}", res.unwrap());
  // "Carrer de Calatrava, 68, 08017 Barcelona, Spain"

  println!("{:?}", oc.remaining_calls());
  // Some(2494)

Address to coordinates (forward geocoding)

use geocoding::{Opencage, Forward, Point};

fn main() {
  let oc = Opencage::new("YOUR-API-KEY".to_string());
  let address = "Schwabing, München";
  // no need to URI encode, library takes care of it

  let res: Vec<Point<f64>> = oc.forward(&address).unwrap();
  let first_result = &res[0];

  println!("{longitude}, {latitude}", longitude = first_result.x(), latitude = first_result.y());
  // 11.5761796, 48.1599218

Start your free trial

2,500 geocoding API requests per day.

No credit card required.