All tutorials

NodeJS

intermediate

The Node.js API wrapper is useful for Node.js developers who wish to seamlessly integrate the what3words API into their Node.js applications, without the hassle of having to manage the low level API calls themselves. We have now added improved support for use within both browser and node based environments.

The what3words API is a fast, simple interface that 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

You will need a what3words API key to complete this tutorial.

2

Installation

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

npm install @what3words/api
Copied
yarn add @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.

3

Setup

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

const what3words = require("@what3words/api");

const apiKey = '<YOUR_API_KEY>';
const config = {
  host: 'https://api.what3words.com',
  apiVersion: 'v3',
}
const transport = 'fetch'; // or you can use 'axios'
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.

ClientRequest consists of the following properties:

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

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:

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

npm:

npm install isomorphic-unfetch
Copied

or

npm install axios
Copied
yarn add isomorphic-unfetch
Copied

or

yarn add 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

async function customTransport(request: ClientRequest): Promise<TransportResponse> {
  const { method, host, url, query = {}, headers = {}, body = {}, format } = request;
  return superagent[method](`${host}${url}`)
    .query({ ...query, format })
    .send(body)
    .set(headers)
    .end((err, res) => {
      if (err) throw err;
      const reponse: TransportResponse = {
        status: res.status,
        statusText: res.
        headers: res.headers,
        body: res.body,
      };
      return response;
    })
}

const service = what3words(API_KEY, config, { transport: customTransport });
service.availableLanguages()
  .then(({ languages }) => console.log('Available languages', languages));
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.520847, -0.195521):

import { ConvertTo3waClient, ConvertTo3waOptions, ConvertTo3waResponse } from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: ConvertTo3waClient = ConvertTo3waClient.init(API_KEY)
const options: ConvertTo3waOptions = { lat: 51.520847, lng: -0.195521 };
client.run(options)
    .then((res: ConvertTo3waResponse) => 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, ConvertToCoordinatesResponse } from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: ConvertToCoordinatesClient = ConvertToCoordinatesClient.init(API_KEY)
const options: ConvertToCoordinatesOptions = { words: 'filled.count.soap' };
client.run(options)
  .then((res: ConvertToCoordinatesResponse) => 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 { ApiVersion, AutosuggestClient, AutosuggestOptions, AutosuggestResponse } from '@what3words/api';

const API_KEY: string = '<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 "${autosuggestOptions.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, GridSectionResponse } from '@what3words/api';

const API_KEY = '<YOUR_API_KEY>';
const client: AvailableLanguagesClient = AvailableLanguagesClient.init(API_KEY);
const options: GridSectionOptions = {
  southwest: { lat: 52.208867, lng: 0.117540 },
  northeast: { lat: 52.207988, lng: 0.116126 }
};
client.run(options)
    .then((res: GridSectionResponse) => 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

Related tutorials

Back to top