Rust Geocoding Tutorial

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

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

Before we dive in to the tutorial ...

You will need to sign up for an OpenCage API key.

Spend two minutes ...

Ok, ready?

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 this to your existing `Cargo.toml` file:

[dependencies]
geocoding = "0.0.3"

Coordinates to address

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

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

fn main() {
  let oc = Opencage::new("YOUR-API-KEY".to_string());
  let address = "Schwabing, München";
  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
}

Further Reading

Start your free trial

2,500 API requests per day.

No credit card required.