All tutorials
Java
The Java API wrapper is useful for Java developers who wish to seamlessly integrate the what3words API into their Java applications, without the hassle of having to manage the low level API calls themselves.
A full example of how to integrate the what3words Java wrapper is available in our
Java Github repository
The library is available through Maven Central. Please add one of the following to either your pom.xml
or gradle.build
files.
Maven:
<dependency> <groupId>com.what3words</groupId> <artifactId>w3w-java-wrapper</artifactId> <version>3.1.17</version> </dependency>
Using Gradle:
implementation 'com.what3words:w3w-java-wrapper:3.1.17'
Instantiate an instance of What3WordsV3, from which all API requests can be made
// For all requests a what3words API key is needed What3WordsV3 api = new What3WordsV3("what3words-api-key");
In the case that you run our Enterprise Suite API Server yourself, you may specify the URL to your server like so:
// In the case that you run our Enterprise Suite API Server yourself, you may specify the URL to your own server like so: What3WordsV3 api = new What3WordsV3("what3words-api-key", "https://api.yourserver.com/v3/");
Additionally, if you run the Enterprise Suite API Server there is another optional setup()
parameter: customHeaders
. Use this if you need to send custom headers to your server:
/** * Additionally, if you run the Enterprise Suite API Server there is another optional setup() parameter: customHeaders. * Use this if you need to send custom headers to your own server: */ Map<String, String> headers = new HashMap<String, String>(); headers.put("Name1", "Value1"); headers.put("Name2", "Value2"); What3WordsV3 api = new What3WordsV3("what3words-api-key", "https://api.yourserver.com/v3/", headers);
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.484463, -0.195405
):
// Convert coordinates to a 3 word address ConvertTo3WA words = api.convertTo3wa(new Coordinates(51.484463, -0.195405)) .language("en") .execute(); System.out.println("Words: " + words);
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
:
// Convert a 3 word address to coordinates ConvertToCoordinates coordinates = api.convertToCoordinates("filled.count.soap") .execute(); System.out.println("Coordinates: " + coordinates);
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:
Autosuggest autosuggest = api.autosuggest("fun.with.code") .execute(); System.out.println("Autosuggest: " + autosuggest);
Code example AutoSuggest, clipping the results returned to the United Kingdom and Belgium:
Autosuggest autosuggest = api.autosuggest("fun.with.code") .clipToCountry("GB", "BE") .execute(); System.out.println("Autosuggest: " + autosuggest);
Code example AutoSuggest, Focus on (51.4243877,-0.34745
).
Autosuggest autosuggest = api.autosuggest("fun.with.code") .focus(new Coordinates(51.4243877,-0.34745)) .execute(); System.out.println("Autosuggest: " + autosuggest);
Code example AutoSuggest, with Generic Voice input type.
Autosuggest autosuggest = api.autosuggest("fun with code") .inputType(AutosuggestInputType.GENERIC_VOICE) .language("en") .execute(); System.out.println("Autosuggest: " + autosuggest);
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 (51.527649, -0.191746
) in the south-west, and (51.515900, -0.212517
in the north-east:
// Obtain a grid section within the provided bounding box GridSection gridSection = api.gridSection( new BoundingBox( new Coordinates(51.515900, -0.212517), new Coordinates(51.527649, -0.191746) ) ).execute(); System.out.println("Grid section: " + gridSection);
Serializing To GeoJSON
If GeoJSON format is required (you are using on a map in an app for example) a function such as geoJsonSerializer
can be added. This should be registered to Gson as a TypeAdapter
and then you can then serialize the objects returned from the wrapper into GeoJSON.
JsonSerializer<GridSection> geoJsonSerializer = api.getGridSectionJsonSerializer(); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(GridSection.class, geoJsonSerializer); Gson geoJsonGson = gsonBuilder.create(); String geoJson = geoJsonGson.toJson(gridSection);
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.
// Obtain the list of available languages AvailableLanguages languages = api.availableLanguages().execute(); System.out.println("Languages: " + languages);
Handling errors
Errors returned from the API can be caught with the wrapper through the use of a catch
function.
Within the catch
function, code
and message
values which represent the error, are accessible from the error
object parameter
Autosuggest autosuggest = api.autosuggest("freshen.overlook.clo") .clipToCountry("fr") .execute(); if (autosuggest.isSuccessful()) { ... } else { // An error occurred What3WordsError error = autosuggest.getError(); if (error == What3WordsError.BAD_CLIP_TO_COUNTRY) { // Invalid country clip is provided System.out.println("BadClipToCountry: " + error.getMessage()); } }
This section introduces RegEx functions that can assist with checking and finding possible what3words addresses in strings. The three main functions covered are:
isPossible3wa
– Match what3words address format;findPossible3wa
– Find what3words address in Text;isValid3wa
– Verify a what3words address with the API;
isPossible3wa
Our API wrapper RegEx function “isPossible3wa
” can be used 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 isValid3wa
to verify validity.
public class What3WordsExample { public static void main(String[] args) { // Example what3words addresses String[] addresses = {"filled.count.soap", "not a 3wa", "not.3wa address"}; // Check if the addresses are possible what3words addresses for (String address : addresses) { boolean isPossible = What3WordsV3.isPossible3wa(address); System.out.println("Is '" + address + "' a possible what3words address? " + isPossible); } } }
Expected Output
- isPossible3wa(“filled.count.soap”) returns
true
- isPossible3wa(“not a 3wa”) returns
false
- isPossible3wa(“not.3wa address”)returns
false
findPossible3wa
Our API wrapper RegEx function “findPossible3wa
” 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
isValid3wa
to verify validity. - This function is designed to work across languages but do not work for
Vietnamese (VI)
due to spaces within words.
public class What3WordsExample { public static void main(String[] args) { // Example texts String[] 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 at" }; // Check each text for possible what3words addresses for (String text : texts) { List<String> possibleAddresses = What3WordsV3.findPossible3wa(text); System.out.println("Possible what3words addresses in '" + text + "': " + possibleAddresses); } } }
Expected Output
- findPossible3wa(“Please leave by my porch at filled.count.soap”) returns
['filled.count.soap']
- findPossible3wa(“Please leave by my porch at filled.count.soap or deed.tulip.judge”) returns
['filled.count.soap', 'deed.tulip.judge']
- findPossible3wa(“Please leave by my porch at”) returns
[]
isValid3wa
Our API wrapper RegEx function “isValid3wa
” 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.
public class What3WordsExample { public static void main(String[] args) { // Initialize the What3Words API with your API key What3WordsV3 api = new What3WordsV3("YOUR_API_KEY"); // Example addresses String[] addresses = { "filled.count.soap", "filled.count.", "coding.is.cool" }; // Check if the addresses are valid what3words addresses for (String address : addresses) { boolean response = api.isValid3wa(address); if (response.isSuccessful() && response.getIsValid()) { System.out.println(address + " is a valid what3words address"); } else if (response.isSuccessful() && !response.getIsValid()) { System.out.println(address + " is an invalid what3words address"); } else { System.out.println("isValid3wa error: " + response.getError().getKey() + " " + response.getError().getMessage()); } } } }
Expected Outputs
- isValid3wa(“filled.count.soap”) returns
True
- isValid3wa(“filled.count.”) returns
False
- isValid3wa(“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 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. Please upgrade your usage plan, or contact support@what3words.com" } }
For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.
The example below takes the concepts described above, and turns some of them into a complete example. Here we take a partial 3 word address and pass it into AutoSuggest – clipping the results to consider only addresses in France, setting a focus of Paris, and returning a single result
We then take the result and convert the 3 word address to coordinates, and find the nearest place.
// For all requests a what3words API key is needed What3WordsV3 api = new What3WordsV3("what3words-api-key"); Autosuggest autosuggest = api.autosuggest("freshen.overlook.clo") .clipToCountry("FR") .focus(new Coordinates(48.856618, 2.3522411)) .nResults(1) .execute(); if (autosuggest.isSuccessful()) { String words = autosuggest.getSuggestions().get(0).getWords(); System.out.printf("Top 3 word address match: %s%n", words); ConvertToCoordinates convertToCoordinates = api.convertToCoordinates(words).execute(); if (convertToCoordinates.isSuccessful()) { System.out.printf("WGS84 Coordinates: %f, %f%n", convertToCoordinates.getCoordinates().getLat(), convertToCoordinates.getCoordinates().getLng()); System.out.printf("Nearest Place: %s%n", convertToCoordinates.getNearestPlace()); } else { What3WordsError error = autosuggest.getError(); if (error == What3WordsError.INTERNAL_SERVER_ERROR) { // Server Error System.out.println("InternalServerError: " + error.getMessage()); } else if (error == What3WordsError.NETWORK_ERROR) { // Network Error System.out.println("NetworkError: " + error.getMessage()); } } } else { What3WordsError error = autosuggest.getError(); if (error == What3WordsError.BAD_CLIP_TO_COUNTRY) { // Invalid country clip is provided System.out.println("BadClipToCountry: " + error.getMessage()); } else if (error == What3WordsError.BAD_FOCUS) { // Invalid focus System.out.println("BadFocus: " + error.getMessage()); } else if (error == What3WordsError.BAD_N_RESULTS) { // Invalid number of results System.out.println("BadNResults: " + error.getMessage()); } else if (error == What3WordsError.INTERNAL_SERVER_ERROR) { // Server Error System.out.println("InternalServerError: " + error.getMessage()); } else if (error == What3WordsError.NETWORK_ERROR) { // Network Error System.out.println("NetworkError: " + error.getMessage()); } else { System.out.println(error + ": " + error.getMessage()); } }