All tutorials

Java

intermediate

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.

The what3words API is a fast, simple interface which allows you to convert 3 word addresses such as ///index.home.raft to latitude and longitude coordinates such as (-0.203586, 51.521251) and vice versa. It features a powerful autosuggest function, which can validate and autocorrect user input and limit it to certain geographic areas (this powers the search box on our map site). It allows you to request a section of the what3words grid (which can be requested as GeoJSON for easy display on online maps), and to request the list of all languages supported by what3words. For advanced users, autosuggest can be used to post-process voice output. See links on the left to navigate.

All coordinates are latitude,longitude pairs in standard WGS-84 (as commonly used worldwide in GPS systems). All latitudes must be in the range of -90 to 90 (inclusive).

1
2

Installation

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>
Copied

Gradle:

implementation 'com.what3words:w3w-java-wrapper:3.1.17'
Copied
3

Setup

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");
Copied
4

Usage

Convert to 3 word address

This function converts coordinates (expressed as latitude and longitude) to a 3 word address.

More information about convertTo3wa, including returned results is available in the what3words REST API documentation.

Find the words for (51.508344,0.12549900):

// Convert coordinates to a 3 word address
ConvertTo3WA words = api.convertTo3wa(new Coordinates(51.508344, -0.12549900))
        .language("en")
        .execute();
System.out.println("Words: " + words);
Copied

Convert to coordinates

This function converts a 3 word address to a position, expressed as coordinates of latitude and longitude.

This function takes the words parameter as a string of 3 words '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);
Copied

AutoSuggest

When presented with a 3 word address that 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.

Example: Basic Autosuggest call

Autosuggest autosuggest = api.autosuggest("fun.with.code")
        .execute();
System.out.println("Autosuggest: " + autosuggest);
Copied

Example: AutoSuggest, clipping the results returned to France and Germany

Autosuggest autosuggest = api.autosuggest("fun.with.code")
        .clipToCountry("FR", "DE")
        .execute();
System.out.println("Autosuggest: " + autosuggest);
Copied

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);
Copied

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);
Copied

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);
Copied

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);  
Copied

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);
Copied

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());
    }
}
Copied
5

RegEx functions

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);
        }
    }
}
Copied

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);
        }
    }
}
Copied

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());
            }
        }
    }
}
Copied

Related tutorials