Rust

Mapricot's API is plain HTTPS and JSON, so Rust needs no Mapricot crate to call it. This page uses reqwest and serde_json to call each API: geocoding, places, routing, and IP geolocation, and shows where the free map tiles fit. It was tested with Rust 1.97, reqwest 0.13, and serde_json 1.0.

Set up

Add the crates to your project:

cargo add reqwest --features blocking,json,query
cargo add serde_json

Create a server key in the dashboard with the products you'll use: Places for geocoding and places, Routing, and IP geolocation. Set it as an environment variable, so it stays out of your code:

export MAPRICOT_KEY="mapricot_sk_…"

Then add get and post functions that send the key with every request, retry when the API is busy, and return an error for error responses. They use reqwest's blocking client, to keep the examples short; in async code, reqwest::Client has the same methods, with .await. The examples below go in main:

use std::{error::Error, thread, time::Duration};

use reqwest::blocking::{Client, RequestBuilder};
use serde_json::{json, Value};

type Result<T> = std::result::Result<T, Box<dyn Error>>;

fn get(client: &Client, path: &str, query: &[(&str, &str)]) -> Result<Value> {
    send(client.get(format!("https://api.mapricot.com{path}")).query(query))
}

fn post(client: &Client, path: &str, body: &Value) -> Result<Value> {
    send(client.post(format!("https://api.mapricot.com{path}")).json(body))
}

fn send(request: RequestBuilder) -> Result<Value> {
    let request = request
        .bearer_auth(std::env::var("MAPRICOT_KEY")?)
        .timeout(Duration::from_secs(30));
    for attempt in 1.. {
        let response = request.try_clone().ok_or("request can't be retried")?.send()?;
        let status = response.status();
        if (status == 429 || status == 503) && attempt < 4 {
            thread::sleep(Duration::from_secs(1 << attempt));
            continue;
        }
        let body: Value = response.json()?;
        if !status.is_success() {
            let message = body["error"]["message"].as_str().unwrap_or_default();
            return Err(format!("Mapricot returned {}: {message}", status.as_u16()).into());
        }
        return Ok(body);
    }
    unreachable!()
}

fn main() -> Result<()> {
    let client = Client::new();
    // The examples go here.
    Ok(())
}

Geocode an address

/v1/search turns an address or place name into coordinates:

let search = get(&client, "/v1/search", &[("q", "128 SW 3rd Ave, Portland"), ("limit", "1")])?;
for result in search["results"].as_array().unwrap() {
    println!("{} {} {}", result["label"].as_str().unwrap(), result["lat"], result["lon"]);
}
128 SW 3rd Avenue, Portland, OR, USA 45.521736 -122.673276

Each result also has its address in parts under address, and a type, such as address, street, or locality, that says how exact the match is. To limit results to some countries, add ("country", "US,CA"). Geocoding lists every parameter and field.

Find the address at a point

/v1/reverse turns coordinates into the nearest address:

let reverse = get(&client, "/v1/reverse", &[("lat", "45.5217"), ("lon", "-122.6733"), ("limit", "1")])?;
let nearest = &reverse["results"][0];
println!("{} {}", nearest["label"].as_str().unwrap(), nearest["distanceMeters"]);
128 SW 3rd Avenue, Portland, OR, USA 4

Suggest places as someone types

/v1/autocomplete takes the text typed so far. focus ranks results near a point first:

let suggestions = get(&client, "/v1/autocomplete", &[("q", "stumpt"), ("focus", "45.52,-122.68"), ("limit", "1")])?;
let suggestion = &suggestions["results"][0];
let id = suggestion["id"].as_str().unwrap();
println!("{} {id}", suggestion["label"].as_str().unwrap());
Stumptown Coffee Roasters, Portland, OR, USA mp_b3BlbnN0cmVldG1hcDp2ZW51ZTpub2RlLzExOTg2MjI2NjYw

Find places nearby

/v1/nearby lists places of a category around a point, nearest first:

let query = [("lat", "45.52"), ("lon", "-122.68"), ("category", "food:coffee_shop"), ("radius", "1000"), ("limit", "1")];
let nearby = get(&client, "/v1/nearby", &query)?;
for place in nearby["results"].as_array().unwrap() {
    println!("{} {}", place["name"].as_str().unwrap(), place["distanceMeters"]);
}
Public Domain 37

Look up a place by ID

Every result has an id. Save it, and /v1/places/{id} fetches that place again later:

let saved = get(&client, &format!("/v1/places/{id}"), &[])?;
println!("{}", saved["result"]["label"].as_str().unwrap());
Stumptown Coffee Roasters, Portland, OR, USA

Get a route

/v1/route takes a JSON body with two to 20 waypoints and a mode of drive, walk, or bicycle:

let body = json!({
    "waypoints": [{ "lat": 43.7396, "lon": 7.4275 }, { "lat": 43.734, "lon": 7.4222 }],
    "mode": "walk",
});
let routes = post(&client, "/v1/route", &body)?;
let route = &routes["routes"][0];
println!("{} {}", route["distanceMeters"], route["durationSeconds"]);
1044 739

Distances are in meters and times in seconds. When no path connects the waypoints, routes is empty. The route's line is in polyline, encoded with six decimal places, so decode it with precision 6, as decoding a route polyline explains.

Look up an IP address

/v1/ip/{ip} gives the approximate location of an IPv4 or IPv6 address:

let location = get(&client, "/v1/ip/8.8.8.8", &[])?;
println!("{} {}", location["city"].as_str().unwrap(), location["countryCode"].as_str().unwrap());
Mountain View US

Show a map

Map tiles are free and need no key. MapLibre GL JS draws them in the browser from https://tiles.mapricot.com/styles/light.json, so Rust on a server doesn't fetch them: send your results to a web page, and draw them there, as Map tiles shows. MapLibre takes coordinates as [lon, lat].

Errors and retries

send returns an error for any error response, with the status and the API's message:

if let Err(error) = get(&client, "/v1/search", &[("q", "")]) {
    println!("{error}");
}
Mapricot returned 400: The service rejected the request.

It retries 429 and 503 responses up to three times, waiting 2, 4, then 8 seconds. Errors aren't billed, so retrying them costs nothing. A 429 that keeps coming back can also mean the account is out of credit. Each account has a limit on requests in progress at once, so send requests one at a time or a few at once. The API reference lists every status.