Rust Geocoding Tutorial

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 geocoding API key.

Then please 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.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
}

Further Reading

Start your free trial

2,500 geocoding API requests per day.

No credit card required.