All tutorials
Rust
The Rust wrapper is useful for Rust developers who wish to seamlessly integrate the what3words Public API into their Rust applications, without the hassle of managing the low-level API calls themselves.
A full example of how to integrate the what3words Rust wrapper is available in our
Rust Github repository
To install what3words, simply:
$ cargo add what3words-api
The functions are asynchronous by default, but this crate supports synchronous functions as well, simply enable sync
feature when adding the crate to your project.
cargo add what3words-api --features=sync
Note: Ensure that you have an async runtime installed such as tokio
except when sync
feature is enabled.
Once you have the API Key, you can initialise the wrapper like this:
let wrapper = what3words_api::What3words::new("YOUR_API_KEY_HERE");
You can also pass a different hostname if you have your own self-hosted what3words API.
let wrapper = what3words_api::What3words::new("YOUR_API_KEY_HERE").hostname("https://your.what3words.api/v3");
You can also set configure your own headers:
let wrapper = what3words_api::What3words::new("YOUR_API_KEY_HERE").header("X-Foo", "Bar");
Convert to what3words address
This function converts coordinates (expressed as latitude and longitude) to a what3words address.
More information about ConvertTo3wa
, including returned results is available in the what3words REST API documentation.
Find the words for (51.520847, -0.195405
):
let convert_to_3wa = what3words_api::ConvertTo3wa::new(51.520847, -0.195521).language("oo").locale("oo_cy");
Here is an example:
use what3words_api::{Address, AddressGeoJson, ConvertTo3wa, What3words}; let w3w = What3words::new("YOUR_API_KEY_HERE"); let convert_to_3wa = ConvertTo3wa::new(51.520847, -0.195521).language("mn").locale("mn_la"); let address_json: Address = w3w.convert_to_3wa::<Address>(&convert_to_3wa); println!("{:?}", address_json.words); // "seruuhen.zemseg.dagaldah" let convert_to_3wa = ConvertTo3wa::new(51.520847, -0.195521); let address_geojson: Address = w3w.convert_to_3wa::<Address>(&convert_to_3wa); println!("{:?}", address_geojson.features); // [Feature { bbox: Some[-0.195543, 51.520833], ..., }]
Note: It is required to specify the type annotation for this function which will allow you to choose between json
and geojson
format. Using Address
will use json
(default) and AddressGeoJson
will use geojson
.
Convert to coordinates
This function converts a what3words address to a position, expressed as coordinates of latitude and longitude.
It takes the words parameter as a string of a what3words 'table.book.chair'
More information about ConvertToCoordinates
, including returned results is available in the what3words REST API documentation.
Find the words for ///filled.count.soap
:
let convert_to_coordinates = what3words_api::ConvertToCoordinates::new("filled.count.soap").locale("zh_tr");
Here is an example:
use what3words_api::{Address, AddressGeoJson, ConvertToCoordinates, What3words}; let w3w = What3words::new("YOUR_API_KEY_HERE"); let convert_to_coordinates = ConvertToCoordinates::new("產權.絕緣.墨鏡").locale("zh_tr"); let address_json: Address = w3w.convert_to_coordinates::<Address>(&convert_to_coordinates); println!("{:?}", address_json.coordinates); // Coordinates { lat: 51.520847, lng: -0.195521 } let convert_to_coordinates = ConvertToCoordinates::new("filled.count.soap"); let address_geojson: AddressGeoJson = w3w.convert_to_coordinates::<AddressGeoJson>(&convert_to_coordinates); println!("{:?}", address_geojson.features); // [Feature { bbox: Some[-0.195543, 51.520833], ..., }]
Note: It is required to specify the type annotation for this function which will allow you to choose between json
and geojson
format. Using Address
will use json
(default) and AddressGeoJson
will use geojson
.
AutoSuggest
When presented with a what3words address which may be incorrectly entered, AutoSuggest returns a list of potential correct 3 word addresses. It needs the first two words plus at least the first character of the third word to produce suggestions.
This method provides corrections for mis-typed words (including plural VS singular), and words being in the wrong order.
Optionally, clipping can narrow down the possibilities, and limit results to:
- One or more countries
- A geographic area (a circle, box or polygon)
This dramatically improves results, so we recommend that you use clipping if possible.
To improve results even further, set the Focus
to user’s current location. This will make AutoSuggest
return results which are closer to the user.
More information about AutoSuggest
, including returned results is available in the what3words REST API documentation.
Code example Simple basic call:
let autosuggest = what3words_api::Autosuggest::new("filled.count.so");
Code example AutoSuggest, clipping the results returned to the United Kingdom and Belgium:
let autosuggest = what3words_api::Autosuggest::new("filled.count.so").clip_to_country(&["GB","BE"])
Code example AutoSuggest, Focus on (51.4243877,-0.34745
).
let autosuggest = what3words_api::Autosuggest::new("filled.count.so").focus(&Coordinates::new(51.4243877, -0.34745));
Code example AutoSuggest, with Generic Voice input type.
use std::env; use what3words_api::{Autosuggest, What3words}; fn main() { let api_key = env::var("W3W_API_KEY").expect( "Please ensure that W3W_API_KEY is added to your environment variables.\nRun `W3W_API_KEY=<YOUR_API_KEY> cargo run --example wrapper-demo` from bash/zsh or `$Env:W3W_API_KEY=<YOUR_API_KEY>; cargo run --example wrapper-demo` from PowerShell.", ); let w3w = What3words::new(&api_key); let autosuggest_option = Autosuggest::new("filled.count.soa") .input_type("generic-voice") .language("en"); let result = w3w.autosuggest(&autosuggest_option); print!("Result: {:?}", result); }
Here is a full AutoSuggest example:
use what3words_api::{Autosuggest, AutosuggestResult, What3words}; let w3w = What3words::new("YOUR_API_KEY_HERE"); let autosuggest_option = Autosuggest::new("filled.count.so").focus(&Coordinates::new(51.520847, -0.195521)); let autosuggest: AutosuggestResult = w3w.autosuggest(&autosuggest_option); println!("{:?}", autosuggest.suggestions); // [Suggestion { words: "filled.count.soap", ..., ... }, ..., ...]
Grid section
Grid section returns a section of the what3words 3m x 3m grid as a set of horizontal and vertical lines covering the requested area, which can then be drawn onto a map.
The requested box must not exceed 4km from corner to corner, or a BadBoundingBoxTooBig
error will be returned.
More information about GridSection
, including returned results is available in the what3words REST API documentation.
Get a grid for 52.207988,0.116126
) in the south west, and 52.208867,0.117540
in the north east:
use what3words_api::{BoundingBox, GridSection, GridSectionGeoJson, What3words}; let w3w: What3words = What3words::new("YOUR_API_KEY_HERE"); // json format let grid_section_json: GridSection = w3w.grid_section::<GridSection>(&BoundingBox::new(52.207988,0.116126,52.208867,0.117540)); println!("{:?}", &grid_section_json.lines[0]); // Line { start: Coordinates { lat: 52.20801, lng: 0.116126 }, end: Coordinates { lat: 52.20801, lng: 0.11754 } } // geojson format let grid_section_geojson: GridSectionGeoJson = w3w.grid_section::<GridSectionGeoJson>(&BoundingBox::new(52.207988,0.116126,52.208867,0.117540)); println!("{:?}", &grid_section_geojson.features); // [Features { geometry: ..., }, ..., ..., kind: "Feature"]
Note: It is required to specify the type annotation for this function which will allow you to choose between json
and geojson
format. Using GridSection
will use json
(default) and GridSectionGeoJson
will use geojson
.
Available languages
This function returns the currently supported languages. It will return the two letter code, and the name of the language both in that language and in English.
More information about AvailableLanguages
, including returned results is available in the what3words REST API documentation.
use what3words_api::{AvailableLanguages, What3words}; let w3w: What3words = What3words::new("YOUR_API_KEY_HERE"); let available_languages: AvailableLanguages = w3w.available_languages(); println!("{:?}", available_languages.languages); // [Language { code: "en", ..., ... }, ..., ... ]
Handling errors
In Rust, error handling is managed using the Result and Option types, which encapsulate potential success (Ok or Some) and failure (Err or None) outcomes. The what3words-api
Rust crate adheres to this convention, returning a Result type for operations that may fail.
To handle errors effectively using this crate, you can utilize pattern matching to differentiate between successful and erroneous outcomes. Here’s an example demonstrating how to handle errors when converting a what3words address to coordinates:
use what3words_api::What3words; fn main() { // Initialize the what3words API with your API key let api_key = "YOUR_API_KEY_HERE"; let w3w = What3words::new(api_key); // Example 3-word address let address = "filled.count.soap"; // Attempt to convert the 3-word address to coordinates match w3w.convert_to_coordinates(address) { Ok(coordinates) => { println!("Coordinates for '{}': {:?}", address, coordinates); } Err(e) => { eprintln!("Error converting '{}': {}", address, e); } } }
Explanation:
Initialisation: The what3words struct is initialised with your API key. Ensure you replace “YOUR_API_KEY_HERE” with your actual what3words API key.
Conversion Attempt: The convert_to_coordinates method is called with the what3words address. This method returns a Result, which can be either:
- Ok(coordinates): Contains the coordinates if the conversion is successful.
- Err(e): Contains the error if the conversion fails.
Error Handling: The match statement is used to handle both success and error cases:
- On success, the coordinates are printed.
- On error, the error’s code and message are accessed and printed to the standard error output.
This approach ensures that your application can handle potential errors gracefully, such as network issues, invalid API keys, or incorrect what3words addresses.
For more detailed information on error handling in Rust, you can refer to the official Rust documentation on Error Handling.
This section introduces RegEx functions that can assist with checking and finding possible what3words addresses in strings. The three main functions covered are:
is_possible_3wa
– Match what3words address format;find_possible_3wa
– Find what3words address in Text;is_valid_3wa
– Verify a what3words address with the API;
is_possible_3wa
Our API wrapper RegEx function “is_possible_3wa
” can be used to detect if a text string (like “filled.count.soap
“) in the format of a what3words address without having to ask the API. This functionality checks if a given string could be a what3words address. It returns true if it could be, otherwise false.
Note: This function checks the text format but not the validity of a what3words address. Use is_valid_3wa
to verify validity.
use what3words_api::What3words; fn main() { // Initialize the what3words API with your API key let api_key = "YOUR_API_KEY_HERE"; let w3w = What3words::new(api_key); // Example what3words addresses let addresses = [ "filled.count.soap", "not a 3wa", "not.3wa address", ]; // Check if the addresses are possible what3words addresses for address in &addresses { let is_possible = w3w.is_possible_3wa(address); println!("Is '{}' a possible what3words address? {}", address, is_possible); } }
Expected Output
- find_possible_3wa(“filled.count.soap”) returns
true
- find_possible_3wa(“not a 3wa”) returns
false
- find_possible_3wa(“not.3wa address”)returns
false
find_possible_3wa
Our API wrapper RegEx function “find_possible_3wa
” can be used to detect a what3words address within a block of text, useful for finding a what3words address in fields like Delivery Notes
. For example, it can locate a what3words address in a note like “Leave at my front door ///filled.count.soap
”. The function will match if there is a what3words address within the text. If no possible addresses are found, it returns an empty list.
Note:
- This function checks the text format but not the validity of a what3words address. Use
is_valid_3wa
to verify validity. - This function is designed to work across languages but do not work for
Vietnamese (VI)
due to spaces within words.
use what3words_api::What3words; fn main() { // Initialize the what3words API with your API key let api_key = "YOUR_API_KEY_HERE"; let w3w = What3words::new(api_key); // Example texts let texts = [ "Please leave by my porch at filled.count.soap", "Please leave by my porch at filled.count.soap or deed.tulip.judge", "Please leave by my porch", ]; // Check each text for possible what3words addresses for text in &texts { let possible_addresses = w3w.find_possible_3wa(text); println!("Possible what3words addresses in '{}': {:?}", text, possible_addresses); } }
Expected Output
- find_possible_3wa(“Please leave by my porch at filled.count.soap”) returns
['filled.count.soap']
- find_possible_3wa(“Please leave by my porch at filled.count.soap or deed.tulip.judge”) returns
['filled.count.soap', 'deed.tulip.judge']
- find_possible_3wa(“Please leave by my porch at”) returns
[]
is_valid_3wa
Our API wrapper RegEx function “is_valid_3wa
” can be used to determine if a string is a valid what3words address by checking it against the what3words RegEx filter and verifying it with the what3words API.
use what3words_api::What3words; fn main() { // Initialize the what3words API with your API key let api_key = "YOUR_API_KEY_HERE"; let w3w = What3words::new(api_key); // Example addresses let addresses = vec![ "filled.count.soap", "filled.count.", "coding.is.cool", ]; // Check if each address is a valid what3words address for address in addresses { let is_valid = w3w.is_valid_3wa(address); println!("Is '{}' a valid what3words address? {}", address, is_valid); } }
Expected Outputs
- is_valid_3wa(“filled.count.soap”) returns
True
- is_valid_3wa(“filled.count.”) returns
False
- is_valid_3wa(“coding.is.cool”) returns
False
Also make sure to replace <YOUR_API_KEY>
with your actual API key. These functionalities provide different levels of validation for what3words addresses, from simply identifying potential addresses to verifying their existence on Earth.
If you encounter errors or issues related to convert-to-coordinate, convert-to-3wa and grid-section requests while using the Free plan, please check the network panel for the following error message Error 402 payment required
and its response, indicating the need to upgrade to a higher plan:
{ "error": { "code": "QuotaExceeded", "message": "Quota exceeded or API plan does not have access to this feature. Please change your plan at https://accounts.what3words.com/select-plan, or contact support@what3words.com" } }
For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.
Examples can be found in /examples
directory of our Rust Github repository, simply run the following to try it out:
# Blocking $ W3W_API_KEY=<YOUR_API_KEY> cargo run --example sync --features="sync"
use std::env; use what3words_api::{ Address, AddressGeoJson, Autosuggest, AutosuggestSelection, BoundingBox, ConvertTo3wa, ConvertToCoordinates, Coordinates, Error, GridSection, GridSectionGeoJson, What3words, }; fn main() -> Result<(), Error> { let api_key = env::var("W3W_API_KEY").expect( "Please ensure that W3W_API_KEY is added to your environment variables.\nRun `W3W_API_KEY=<YOUR_API_KEY> cargo run --example wrapper-demo` from bash/zsh or `$Env:W3W_API_KEY=<YOUR_API_KEY>; cargo run --example wrapper-demo` from PowerShell.", ); let w3w = What3words::new(&api_key).header("X-Foo", "Bar"); let words = "filled.count.soap"; // ------ CONVERT TO COORDINATES/3WA ------ // ------ Error ------ let address = w3w.convert_to_coordinates::<Address>(&ConvertToCoordinates::new("filled.count")); match address { Ok(address) => println!("Address {:?}", address), Err(error) => println!("Error {:?}", error), } // ------------------- let convert_to_coordinates = ConvertToCoordinates::new(words); let address: Address = w3w.convert_to_coordinates(&convert_to_coordinates)?; println!("Convert to Coordinates Json Format"); println!("{:?}", address); let convert_to_coordinates = ConvertToCoordinates::new(words); let address: AddressGeoJson = w3w.convert_to_coordinates(&convert_to_coordinates)?; println!("Convert to Coordinates GeoJson Format"); println!("{:?}", address); let convert_to_3wa = ConvertTo3wa::new(51.520847, -0.195521); let address: Address = w3w.convert_to_3wa(&convert_to_3wa)?; println!("Convert to 3WA Json Format"); println!("{:?}", address); let convert_to_3wa = ConvertTo3wa::new(51.520847, -0.195521); let address: AddressGeoJson = w3w.convert_to_3wa(&convert_to_3wa)?; println!("Convert to 3WA GeoJson Format"); println!("{:?}", address); // ------ ALL AVAILABLE LANGUAGES ------ let languages = w3w.available_languages()?; println!("Available Languages"); println!("{:?}", languages.languages); // ------ GRID SECTION ------ let grid_section_json: GridSection = w3w.grid_section(&BoundingBox::new(52.207988, 0.116126, 52.208867, 0.117540))?; println!("Grid Section Json Format"); println!("{:?}", grid_section_json); let grid_section_geojson: GridSectionGeoJson = w3w.grid_section(&BoundingBox::new(52.207988, 0.116126, 52.208867, 0.117540))?; println!("Grid Section GeoJson Format"); println!("{:?}", grid_section_geojson); // ------ AUTOSUGGEST ------ let autosuggest_option = Autosuggest::new("filled.count.so").focus(&Coordinates::new(51.520847, -0.195521)); let autosuggest = w3w.autosuggest(&autosuggest_option)?; println!("Autosuggest"); println!("{:?} ", autosuggest); // ------ AUTOSUGGEST WITH COORDINATES ------ let autosuggest_with_coordinates = w3w.autosuggest_with_coordinates(&autosuggest_option); println!("Autosuggest with Coordinates"); match autosuggest_with_coordinates { Ok(autosuggest_with_coordinates) => println!("{:?}", autosuggest_with_coordinates), Err(err) => println!("{:?}", err), } // ------ AUTOSUGGEST SELECTION ------ let selected = autosuggest.suggestions.first().expect("Not found"); match w3w.autosuggest_selection( &AutosuggestSelection::new("f.f.f", selected).options(&autosuggest_option), ) { Ok(_) => println!("Suggested selection sent"), Err(err) => println!("{:?}", err), }; // ------ HELPER FUNCTIONS ------ let is_valid_3wa: bool = w3w.is_valid_3wa("filled.count.soap"); println!("is_valid_3wa [1]: {}", is_valid_3wa); let is_valid_3wa: bool = w3w.is_valid_3wa("filled.count"); println!("is_valid_3wa [2]: {}", is_valid_3wa); let is_valid_3wa: bool = w3w.is_valid_3wa("rust.is.cool"); println!("is_valid_3wa [3]: {}", is_valid_3wa); let did_you_mean: bool = w3w.did_you_mean("filled count soap"); println!("did_you_mean [1]: {}", did_you_mean); let did_you_mean: bool = w3w.did_you_mean("filled-count-soap"); println!("did_you_mean [2]: {}", did_you_mean); let did_you_mean: bool = w3w.did_you_mean("filledcountsoap"); println!("did_you_mean [3]: {}", did_you_mean); let is_possible_3wa: bool = w3w.is_possible_3wa("filled.count.soap"); println!("is_possible_3wa [1]: {}", is_possible_3wa); let is_possible_3wa: bool = w3w.is_possible_3wa("not a 3wa"); println!("is_possible_3wa [2]: {}", is_possible_3wa); let is_possible_3wa: bool = w3w.is_possible_3wa("not.a 3wa"); println!("is_possible_3wa [3]: {}", is_possible_3wa); let all_possible_3wa: Vec<String> = w3w.find_possible_3wa("from index.home.raft to filled.count.soap"); println!("find_possible_3wa [1]: {:?}", all_possible_3wa); let find_possible_3wa: Vec<String> = w3w.find_possible_3wa("Please leave by my porch at filled.count.soap"); println!("find_possible_3wa [2]: {:?}", find_possible_3wa); let find_possible_3wa: Vec<String> = w3w.find_possible_3wa("Please leave by my porch at filled.count.soap or deed.tulip.judge"); println!("find_possible_3wa [3]: {:?}", find_possible_3wa); let find_possible_3wa: Vec<String> = w3w.find_possible_3wa("Please leave by my porch"); println!("find_possible_3wa [4]: {:?}", find_possible_3wa); let find_possible_3wa = w3w.find_possible_3wa("This is a test with filled count soap in it."); println!("find_possible_3wa [5]: {:?}", find_possible_3wa); Ok(()) }