All tutorials

JavaScript SDK

intermediate

The JavaScript SDK 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:

AutoSuggest Component
Map Component

In case you are looking to seamlessly integrate the what3words Public API into your Node.js/Browser-based environment applications, the JavaScript API Wrapper is the right technology for your application.

1
2

Installation

This is the script that is at the core of the component libraries.

To add the core SDK natively to a web document you should add the what3words script tags within the head of your document.

<head>
    <!-- Load the what3words SDK --->
    <script type="module"defer src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.esm.js"></script>
    <script nomodule defer src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.js"></script>
    ...
</head>
Copied

The URL contained in the script tags are the locations of JavaScript files that load everything you need for using the JavaScript API wrapper for the what3words API.

Note: We prefer to use a fixed version for the Production version of your integrations. A specific version can also be specified within the script to ensure a predictable version of the component is loaded, for example @4.8.0. A log of versions can be found here.

It is recommended to set up a callback function to attach the what3words API to the window accessible via window.what3words in the script within your head HTML tag as mentioned below.

<head>
    <!-- Load the what3words SDK --->
    <script type="module"defer src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.esm.js"></script>
    <script nomodule defer src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.js&callback=initW3w"></script>
    <script>
      // Set the callback function for what3words
      window.w3w = {
          callback: "initW3w"
      };
    </script>
    ...
</head>
Copied

To initiate this function pass a parameter e.g. sdk to the callback function initW3w.

Also, make sure to set up the what3words API key with the setApiKey function by replacing the "YOUR-API-KEY" with your application’s API key. Sign up to obtain your free API key.

Otherwise you can add our AutoSuggest component or Map component to your page with our component tags.

function initW3w(sdk) {
  // Set what3words API key
  sdk.api.setApiKey('YOUR-API-KEY');

  // OR you can also just use the global window object at this point
  // window.what3words.api.setApiKey("YOUR-API-KEY");

  sdk.api
    .autosuggest({
        input: 'freshen.overlook.clo',
        nFocusResults: 1,
        clipToCountry: ['FR'],
        focus: { lat: 48.856618, lng: 2.3522411 },
        nResults: 1,
        language: 'en'
    })
    .then(function (response) {
        console.log(response);
    });

  sdk.api
    .convertToCoordinates({
        words: 'filled.count.soap',
        format: 'json' // or format: 'geojson'
    })
    .then(function (response) {
        console.log(response);  
    });

  sdk.api
    .convertTo3wa ({
      coordinates: { lat: 51.520847, lng: -0.195521 },
      language: 'en',
      format: 'json' // or format: 'geojson'
    })
    .then(function (response) {
      console.log(response);
    });

  sdk.api
    .gridSection({
      boundingBox: {
        southwest: {
          lat: sw.lat,
          lng: sw.lng
        },
        northeast: {
          lat: ne.lat,
          lng: ne.lng
        }
       },
      format: "geojson" // or format: 'json'
      })
    .then(function (data) {
      console.log(data)
    })
    .catch(console.error);
}
Copied
3

Usage

Convert to 3 word address

Convert coordinates, expressed as latitude and longitude to a 3 word address.

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

Return standard response:

/**
* Converts a coordinate to a 3 word address
* @param {Object} coordinates - The coordinate object
* @param {number} coordinates.lat - The latitude
* @param {number} coordinates.lng - The longitude
* @param {string} [language= ‘en’] - The language to return the 3 word address in
* @param {string} [format= ‘json’ | format= ‘geojson’]
* @returns {Promise} Promise 3 word address response
*/

sdk.api
  .convertTo3wa ({
    coordinates: { lat: 51.520847, lng: -0.195521 },
    language: 'en',
    format: 'json' // or format: 'geojson'
  })
  .then(function (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 words parameter as a string of 3 words 'table.book.chair'

More info about convertToCoordinates, including returned results is available in the what3words REST API documentation.

Return standard response:

/**
* Returns coordinates for a 3 word address
* @param {string} words - The 3 word address words to convert to coordinates
* @param {string} [format= ‘json’ | format= ‘geojson’]
* @returns {Promise} - Promise coordinates response
*/

sdk.api
  .convertToCoordinates({
    words: 'filled.count.soap',
    format: 'json' // or format: 'geojson'
  })
  .then(function (response) {
    console.log(response);  
  });
Copied

AutoSuggest

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

Example: Basic Autosuggest call.

/**
* Returns autosuggest results for a search term
* @param {string} input - The input to search for autosuggests
* @param {Object} [options] - The result filter and clipping options
* @param {Object} [options.focus] - The coordinates for the focus of the search
* @param {number} [options.focus.lat] - The latitude of the focus
* @param {number} [options.focus.lng] - The longitude of the focu
* @param {string} [options.nFocusResults] - The number of focused results
* @param {string[]} [options.clipToCountry] - The countries to clip results to
* @param {Object} [options.clipToBoundingBox] - The bounding box to clip results within
* @param {Object} [options.clipToBoundingBox.southwest] - The coordinates of the southwest corner of the clipping box
* @param {Object} [options.clipToBoundingBox.southwest.lat] - The latitude of the southwest corner of the clipping box
* @param {Object} [options.clipToBoundingBox.southwest.lng] - The longitude of the southwest corner of the clipping box
* @param {Object} [options.clipToBoundingBox.northeast] - The coordinates of the northeast corner of the clipping box
* @param {Object} [options.clipToBoundingBox.northeast.lat] - The latitude of the northeast corner of the clipping bo
* @param {Object} [options.clipToBoundingBox.northeast.lng] - The longitude of the northeast corner of the clipping box
* @param {Object} [options.clipToCircle] - The circle to clip results within
* @param {Object} [options.clipToCircle.center] - The center of the circle to clip results within
* @param {number} [options.clipToCircle.center.lat] - The latitude of the center of the circle to clip results within
* @param {number} [options.clipToCircle.center.lng] - The longitude of the center of the circle to clip results within
* @param {number} [options.clipToCircle.radius] - The radius of the circle to clip results within
* @param {number[]} [options.clipToPolygon] - An array of polygon coordinates to clip results within
* @param {string} [options.inputType] - 'text' | 'vocon-hybrid' | 'nmdp-asr' | 'generic-voice'
* @param {string} [options.language] - The language to return autosuggest results in
* @param {boolean} [options.preferLand] - Whether to bias towards results that are over land vs over the sea.
* @returns {Promise} - Promise 3 word address autosuggestions response
*/

sdk.api
  .autosuggest({
    input: 'freshen.overlook.clo',
      language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

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

sdk.api
  .autosuggest({
    input: 'freshen.overlook.clo',
    clipToCountry: ['FR', 'DE'],
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

Example: AutoSuggest, clipping to a circle.

sdk.api
  .autosuggest({
    input: 'freshen.overlook.clo',
    clipToCircle: {center: {lat:51.4243877, lng:-0.34745}, radius:50},
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

Example: AutoSuggest, clipping to a polygon.

sdk.api
  .autosuggest({
    input: 'freshen.overlook.clo',
    clipToPolygon: [{ lat: 51.421, lng: -0.343 }, { lat: 52.6, lng: 2.3324 }, { lat: 54.234, lng: 8.343 }, { lat: 51.421, lng: -0.343 }],
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

Example: AutoSuggest, clipping to a bounding box.

sdk.api
  .autosuggest({
    input: 'fun.with.code',
    clipToBoundingBox:{ 
         southwest: { lat: 51.521, lng: -0.343 },
         northeast: { lat: 52.6, lng: 2.3324 }
    },
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

Example: AutoSuggest, Focus on (51.4243877,-0.34745).

sdk.api
  .autosuggest({
    input: 'fun.with.code',
    focus: {lat:51.4243877, lng:-0.34745},
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

Example: AutoSuggest, Focus on (51.4243877,-0.34745) and then determine how many results within the response it applies to.

sdk.api
  .autosuggest({
    input: 'fun.with.code',
    focus: {lat:51.4243877, lng:-0.34745},
    nFocusResults: 2,
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
Copied

Example: AutoSuggest, with Generic Voice input type.

sdk.api
  .autosuggest({
    input: 'fun.with.code',
    inputType: 'generic-voice',
    language: 'en'
  })
  .then(function (response) {
    console.log(response);
  });
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.

Return standard response:

/**
 * Returns a section of the what3words grid
 * @param {Object} boundingBox - The bounding box for the grid to return
 * @param {Object} [boundingBox.southwest] - The coordinates of the southwest corner of the bounding box
 * @param {Object} [boundingBox.southwest.lat] - The latitude of the southwest corner of the bounding box
 * @param {Object} [boundingBox.southwest.lng] - The longitude of the southwest corner of the bounding box
 * @param {Object} [boundingBox.northeast] - The coordinates of the northeast corner of the bounding box
 * @param {Object} [boundingBox.northeast.lat] - The latitude of the northeast corner of the bounding box
 * @param {Object} [boundingBox.northeast.lng] - The longitude of the northeast corner of the bounding box
 * @param {string} [format= ‘json’ | format= ‘geojson’]
 * @return {Promise} - Promise the grid section
 */

sdk.api
  .gridSection({
    boundingBox: {
      southwest: {
            lat: sw.lat, //replace sw.lat with your south west latitude
            lng: sw.lng //replace sw.lng with your south west longitude
      },
      northeast: {
            lat: ne.lat, //replace ne.lat with your north east latitude
            lng: ne.lng  //replace ne.lat with your north east longitude
      }
    },
    format: "json" // or format:"geojson"
  })
  .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 in English.

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

/**
 * Returns the available languages supported by what3words API
 * @returns {Promise} - Promise the available languages response
 */

sdk.api
  .availableLanguages()
  .then(function (n) {
    console.log("[availableLanguages]", n)
  });
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.

sdk.api
   .convertToCoordinates({ 
      words: 'filled.count.soap',
      format: 'json' // or format: 'geojson'
   })
   .then(function (response) {
      console.log(response);  	
   })
  .catch(function(error) { // catch errors here
      console.log("[code]", error.code);
      console.log("[message]", error.message);
   });
Copied
4

Full example

The example below takes the concepts described in the step-by-step 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 on Paris, and returning a single result. We also show how easy is to implement the AutoSuggest Component instead of using the JavaScript SDK.
We then take the result convert the 3 word address to coordinates, and find the nearest place.

<html>
  <head>
    <title>what3words JavaScript SDK</title>
    <meta charset="utf-8" />
    <script
      type="module"
      async
      src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.esm.js"
    ></script>
    <script
      nomodule
      async
      src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.js&callback=initW3w"
    ></script>
    <script>
      // Set the callback function for what3words
      window.w3w = {
        callback: "initW3w",
      };
    </script>
  </head>
  <body>
    <h3>Add what3words AutoSuggest Component to your page</h3>
    <what3words-autosuggest api_key="YOUR-API-KEY">
      <input type="text" />
    </what3words-autosuggest>
  
    <hr style="margin:30px 0"/>

  <h3>Or programatically access the what3words API</h3>
    <p id="top3wa">Top 3 word address match:</p>
    <p id="coords">WGS84 Coordinates:</p>
    <p id="nearest_place">Nearest Place:</p>
    <script>
      // This function is called when the what3words.js SDK loads by passing `callback` to and the name of the
      // function to call in the script tag above

      function initW3w(sdk) {
        console.log("loaded", sdk);
        // Set w3w API key
        sdk.api.setApiKey("YOUR-API-KEY");
        // OR you can also just use the global window object at this point
        // window.what3words.api.setApiKey("YOUR-API-KEY");
        sdk.api
          .autosuggest({
            input: "freshen.overlook.clo",
            nFocusResults: 1,
            clipToCountry: ["FR"],
            focus: { lat: 48.856618, lng: 2.3522411 },
            nResults: 1,
          })
          .then(function (response) {
            console.log(response);
            var words = response.suggestions[0].words;

            top3wa = document.getElementById("top3wa");
            top3wa.innerHTML += words;

            sdk.api
              .convertToCoordinates({ words: words, format: "json" })
              .then(function (response) {
                console.log(response);
                coords = document.getElementById("coords");
                nearestPlace = document.getElementById("nearest_place");

                coords.innerHTML +=
                  response.coordinates.lat + ", " + response.coordinates.lng;
                nearestPlace.innerHTML += response.nearestPlace;
              });
          })
          .catch(function (error) {
            console.log("[code]", error.code);
            console.log("[message]", error.message);
          });
      }
    </script>
  </body>
</html>
Copied

Related tutorials