All tutorials

JavaScript

intermediate

The JavaScript API wrapper is useful for developers who wish to seamlessly integrate the what3words Public API into their Node.js/Browser-based environment, without the hassle of having to manage the low-level API calls themselves.

Alternatively, there is a JavaScript SDK that uses the JavaScript API Wrapper under the hood, and it supports native web components @what3words/javascript-components (which can also be loaded via CDN), Angular components – @what3words/angular-components, React components – @what3words/react-components and Vue components – @what3words/vue-components.

The components available for you to use are as follows:

1Get an API Key
2Installation

To load the JavaScript wrapper for the what3words API, use npm or yarn:

npm install @what3words/api
Copied

If you wish to use the built-in transports you will also need to install the peer dependencies for them. For more information on the default transports read the section on Transports.

3Setup

First, configure the wrapper including adding your what3words API key:

const what3words,
  { fetchTransport } = require('@what3words/api');

const apiKey = '<YOUR_API_KEY>';
const config = {
  host: 'https://api.what3words.com',
  apiVersion: 'v3',
};
const transport = fetchTransport(); // or you can import 'axiosTransport' instead
const w3wService = what3words(apiKey, config, { transport });

// you can uncomment the following lines to set your api key and config after instantiation of the w3w service
// w3wService.setApiKey(apiKey);
// w3wService.setConfig(config);
Copied

what3words Service

The What3wordsService provides a quick and easy way to instantiate the API clients that can be used to make requests against the what3words API. It also provides helper functions for setting API configuration, such as host and API version and your API key across the what3words API clients.

Clients

The what3words API clients in this library are used to validate request options, serialise and handle request/response and errors against an API endpoint. Each client extends the abstract ApiClient class.

There is a specific client for each request and you can use them independently of the What3wordsService. This can be particularly useful if you want to extend the client behavior, minimise your code, or, in a more extreme example, use a custom transport to handle requests differently in each client.

Every client accepts the following parameters:

ParameterDatatypeDefault value
apiKeystring''
configconfig.hosthttps://api.what3words.com
config.apiVersionv3

Transport

The transport is a function responsible for executing the request against the API. Given a ClientRequest the transport should return a promise that resolves to TransportResponse.

A ClientRequest consists of the following properties:

PropertyDatatype
host*string
url*string
method*get or post
queryobject
headersobject
bodyobject
format*json or geojson. Default: json

A TransportResponse consists of the following properties:

PropertyDatatype
status*number
statusText*string
body*any
headersobject

There are two built-in transports available with this library that you can use; either isomorphic-unfetch or axios. By specifying which transport you would like to use on initialisation of the What3wordsService or a client, if you wish to instantiate a client for yourself.

Built-ins

There are two built-in transports available:

To use either of these you will need to install the peer dependency. By default, isomorphic-unfetch is assumed by the What3wordsService or any instantiated client where no override is provided.

npm install cross-fetch
npm install axios
Copied

Custom

You can provide your own custom transport, if you wish to use another library for handling requests, which might be useful if you have other integrations or you are already using an http library elsewhere.

In order to do so you need to define your own Transport and pass it into the What3wordsService or client to use it.

The custom Transport you create should be a function that accepts a ClientRequest as an argument and returns a promise that resolves to a TransportResponse.

Example

import what3words, { ClientRequest, TransportResponse } from '@what3words/api';
import superagent from 'superagent';

const API_KEY = '<YOUR_API_KEY>';
const config = {}; // This will ensure we do not override the defaults

function customTransport<ResponseType>(
  request: ClientRequest
): Promise<TransportResponse<ResponseType>> {
  const {
    method,
    host,
    url,
    query = {},
    headers = {},
    body = {},
    format,
  } = request;
  return new Promise(resolve =>
    superagent[method](`${host}${url}`)
      .query({ ...query, format })
      .send(body || {})
      .set(headers)
      .end((err, res) => {
        if (err || !res)
          return resolve({
            status: err.status || 500,
            statusText: err.response.text || 'Internal Server Error',
            headers: err.headers || {},
            body: err.response.text || null,
          });
        const response: TransportResponse<ResponseType> = {
          status: res.status,
          statusText: res.text,
          headers: res.headers,
          body: res.body,
        };
        resolve(response);
      })
  );
}

const service = what3words(API_KEY, config, { transport: customTransport });
service
  .availableLanguages()
  .then(({ languages }) => console.log('Available languages', languages));
Copied
4Usage on Browser-based environment

Requirements

There are some requirements to use the JavaScript API wrapper on a browser environment please note the following:

  • esbuild was used to build the project with a dependency on esbuild-plugin-polyfill-node to shim node-specific features to successfully compile for browsers. You may choose to bundle your project with any appropriate tool of your choice, the only requirement as of what3words/api v5.0.1 now is to polyfill the node os built-in.
  • To use the package, run the following command to install the javascript API wrapper and its core dependencies:
npm install -S @what3words/api axios cross-fetch
Copied
  • Alternatively, there is a JavaScript SDK that uses the JavaScript API Wrapper under the hood, and it supports native web components @what3words/javascript-components (which can also be loaded via CDN), Angular components – @what3words/angular-components, React components – @what3words/react-components and Vue components – @what3words/vue-components. The components available for you to use are the AutoSuggest Component and the Map Component.

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.520847, -0.195521):

import what3words, {
  axiosTransport,
  ApiVersion
} from "@what3words/api";

const W3W_API_KEY = "<YOUR_API_KEY>"; //TODO: Add your what3words API key here

// Instantiate what3words instance
window.what3words = what3words(
    "",
    { apiVersion: ApiVersion.Version3 },
    { transport: axiosTransport() },
  );

// Configure what3words JS wrapper
window.what3words.setApiKey(W3W_API_KEY);

// Convert a coordinate to a three word address and retrieve the JSON response from our API
window.what3words
	.convertTo3wa({ 
		coordinates: { lat: 51.520847, lng: -0.195521 },
    language: 'en',
    format: 'json'
	})
	.then((response) => {
    word = response.words;
    console.log(word);
	})

// Convert a coordinate to a three word address and retrieve the GEOJSON response from our API
window.what3words
	.convertTo3wa({ 
		coordinates: { lat: 51.520847, lng: -0.195521 },
    language: 'en',
    format: 'geojson'
	})
	.then((response) => {
    console.log(response);
	})
Copied

Convert to coordinates

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

It takes the word 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:

import what3words, {
  axiosTransport,
  ApiVersion,
  W3W_REGEX,
} from "@what3words/api";

const W3W_API_KEY = "<YOUR_API_KEY>"; //TODO: Add your what3words API key here

// Instantiate what3words instance
window.what3words = what3words(
    "",
    { apiVersion: ApiVersion.Version3 },
    { transport: axiosTransport() },
  );

// Configure what3words JS wrapper
window.what3words.setApiKey(W3W_API_KEY);

const THREE_WORD_ADDRESS = "filled.count.soap";

// Retrieve coordinates for initial three word address in JSON
window.what3words
 .convertToCoordinates({ 
		words: THREE_WORD_ADDRESS,
		format: 'json' // or format: 'geojson' 
	})
 .then((res) => {
      coordinates = res.coordinates;
      console.log(coordinates);
	})

// Retrieve coordinates for initial three word address in GEOJSON
window.what3words
 .convertToCoordinates({ 
		words: THREE_WORD_ADDRESS,
		format: 'geojson' // or format: json' 
	})
 .then((res) => {
      console.log(response);
	})
Copied

AutoSuggest

When presented with a 3 words 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.

import what3words, {
  axiosTransport,
  ApiVersion
} from "@what3words/api";

const W3W_API_KEY = "<YOUR_API_KEY>"; //TODO: Add your what3words API key here

// Instantiate what3words instance
window.what3words = what3words(
    "",
    { apiVersion: ApiVersion.Version3 },
    { transport: axiosTransport() },
  );

// Configure what3words JS wrapper
window.what3words.setApiKey(W3W_API_KEY);

window.what3words
	.autosuggest({
	  input: 'freshen.overlook.clo',
    language: 'en'
	})
	.then(function (response) {
  	  console.log(`suggestions for: ${response}`);
  });
Copied

Grid section

The 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.208867,0.117540) in the south-west, and (52.207988,0.116126) in the north-east:

import what3words, {
  axiosTransport,
  ApiVersion
} from "@what3words/api";

const W3W_API_KEY = "<YOUR_API_KEY>"; //TODO: Add your what3words API key here

// Instantiate what3words instance
window.what3words = what3words(
    "",
    { apiVersion: ApiVersion.Version3 },
    { transport: axiosTransport() },
  );

// Configure what3words JS wrapper
window.what3words.setApiKey(W3W_API_KEY);

// Call the what3words Grid API to obtain the grid squares within the current visible bounding box
window.what3words.
  .gridSection({
	  boundingBox: {
  	    southwest: {
    	      lat: sw.lat(), // replace with SouthWest Latitude coordinates
    	      lng: sw.lng() // replace with SouthWest Longitude coordinates
  	    },
  	    northeast: {
    	      lat: ne.lat(), // replace with NorthEast Latitude coordinates
    	      lng: ne.lng() // replace with NorthEast Longitude coordinates
  	    }
	   },
	format: "json"
  })
  .then(function (data) {
		console.log(data)
  })
  .catch(console.error);
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 English.

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

import what3words, {
  axiosTransport,
  ApiVersion
} from "@what3words/api";

const W3W_API_KEY = "<YOUR_API_KEY>"; //TODO: Add your what3words API key here

// Instantiate what3words instance
window.what3words = what3words(
    "",
    { apiVersion: ApiVersion.Version3 },
    { transport: axiosTransport() },
  );

// Configure what3words JS wrapper
window.what3words.setApiKey(W3W_API_KEY)

// Retrieve and print out supported languages
window.what3words.availableLanguages().then((res) => {
  languages = res.languages;
  console.log(languages);
});
Copied
5Usage on Node.js-based environment

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.520847, -0.195521):

import {
  ConvertTo3waClient,
  ConvertTo3waOptions,
  FeatureCollectionResponse,
  LocationGeoJsonResponse,
  LocationJsonResponse,
} from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: ConvertTo3waClient = ConvertTo3waClient.init(API_KEY);
const options: ConvertTo3waOptions = {
  coordinates: { lat: 51.520847, lng: -0.195521 },
};

// If you want to retrieve the JSON response from our API
client
  .run({ ...options, format: 'json' }) // { format: 'json' } is the default response
  .then((res: LocationJsonResponse) => console.log('Convert to 3wa', res));

// If you want to retrieve the GeoJsonResponse from our API
client
  .run({ ...options, format: 'geojson' })
  .then((res: FeatureCollectionResponse<LocationGeoJsonResponse>) =>
    console.log('Convert to 3wa', res)
  );
Copied

Convert to coordinates

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

It 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:

import {
  ConvertToCoordinatesClient,
  ConvertToCoordinatesOptions,
  FeatureCollectionResponse,
  LocationGeoJsonResponse,
  LocationJsonResponse,
} from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: ConvertToCoordinatesClient =
  ConvertToCoordinatesClient.init(API_KEY);
const options: ConvertToCoordinatesOptions = { words: 'filled.count.soap' };

// If you want to retrieve the JSON response from our API
client
  .run({ ...options, format: 'json' }) // { format: 'json' } is the default response
  .then((res: LocationJsonResponse) =>
    console.log('Convert to coordinates', res)
  );

// If you want to retrieve the GeoJsonResponse from our API
client
  .run({ ...options, format: 'geojson' })
  .then((res: FeatureCollectionResponse<LocationGeoJsonResponse>) =>
    console.log('Convert to coordinates', res)
  );
Copied

AutoSuggest

When presented with a 3 words 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

import {
  AutosuggestClient,
  AutosuggestOptions,
  AutosuggestResponse,
} from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: AutosuggestClient = AutosuggestClient.init(API_KEY);
const options: AutosuggestOptions = {
  input: 'filled.count.s',
};
client
  .run(options)
  .then((res: AutosuggestResponse) =>
    console.log(`suggestions for "${options.input}"`, res)
  );
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 (52.208867,0.117540) in the south west, and (52.207988,0.116126) in the north east:

import {
  GridSectionClient,
  GridSectionOptions,
  FeatureCollectionResponse,
  GridSectionGeoJsonResponse,
  GridSectionJsonResponse,
} from '../src';

const API_KEY = '<YOUR_API_KEY>';
const client: GridSectionClient = GridSectionClient.init(API_KEY);
const options: GridSectionOptions = {
  boundingBox: {
    southwest: { lat: 52.208867, lng: 0.11754 },
    northeast: { lat: 52.207988, lng: 0.116126 },
  },
};

// If you want to retrieve the JSON response from our API
client
  .run({ ...options, format: 'json' }) // { format: 'json' } is the default response
  .then((res: GridSectionJsonResponse) => console.log('Grid Section', res));

// If you want to retrieve the JSON response from our API
client
  .run({ ...options, format: 'geojson' }) // { format: 'json' } is the default response
  .then((res: FeatureCollectionResponse<GridSectionGeoJsonResponse>) =>
    console.log('Grid Section', res)
  );
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.

import {
  AvailableLanguagesClient,
  AvailableLanguagesResponse,
} from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: AvailableLanguagesClient = AvailableLanguagesClient.init(API_KEY);
client
  .run()
  .then((res: AvailableLanguagesResponse) =>
    console.log('Available Languages', res)
  );
Copied
6RegEx 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.

import { AutosuggestClient } from "@what3words/api";

// Initialise the What3Words API with your API key
const API_KEY = 'YOUR_API_KEY';
const client = AutosuggestClient.init(API_KEY);

// Example what3words addresses
const addresses = ["filled.count.soap", "not a 3wa", "not.3wa address"];

// Function to check if the address is a possible what3words address
const checkPossible3wa = (address) => {
  const isPossible = client.isPossible3wa(address);
  console.log(`Is '${address}' a possible what3words address? ${isPossible}`);
};

// Check each address
addresses.forEach(checkPossible3wa);
Copied

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.
import { AutosuggestClient } from "@what3words/api";

const API_KEY = 'YOUR_API_KEY';
const client = AutosuggestClient.init(API_KEY);

// Example texts
const 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"
];

// Function to find possible what3words addresses in text
const findPossible3wa = (text) => {
    return client.findPossible3wa(text);
};

// Check each text for possible what3words addresses
texts.forEach((text) => {
    const possibleAddresses = findPossible3wa(text);
    console.log(`Possible what3words addresses in '${text}':`, possibleAddresses);
});
Copied

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.

import { AutosuggestClient } from "@what3words/api";

const API_KEY = 'YOUR_API_KEY';
const client = AutosuggestClient.init(API_KEY);

// Example addresses
const addresses = [
    "filled.count.soap",
    "filled.count.",
    "coding.is.cool"
];

// Function to check if the address is valid
const checkIsValid3wa = async (address) => {
    try {
        const isValid = await client.isValid3wa(address);
        console.log(`Is '${address}' a valid what3words address? ${isValid}`);
    } catch (error) {
        console.error(`Error validating address '${address}':`, error);
    }
};

// Check each address for validity
addresses.forEach(checkIsValid3wa);
Copied

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.

7Troubleshooting

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

For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.

Related tutorials