Using the JavaScript AutoSuggest Component (v4)

easy

The easiest way to add what3words to your technology is to use one of our components. We have components available for JavaScript, iOS and Android which require minimal development to integrate. The JavaScript component can also be used in React.js, Vue.js and Angular.

The AutoSuggest Component allows users to quickly and correctly input a 3 word address to a form input or search field by providing suggestions as a user types and validation to ensure the input value is a valid 3 word address. The component by default uses the what3words API or can be configured to use a privately hosted instance of the what3words API.

This tutorial steps through how our JavaScript AutoSuggest Component can be added to a website either for static pages or using npm, how it can be customised to refine the 3 word address suggestions displayed and how it can inherit the style of your site.

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.

Find out how else you can access the JavaScript API Wrapper via the window object by using our JavaScript SDK.

Getting started with Christian, what3words Lead Frontend Developer:

Quickstart

The AutoSuggest Component requires just a few lines of code to be added to a form to create a what3words powered input field. Replace YOUR-API-KEY with your what3words API key to get started.

<script type="module" async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.esm.js"></script>
<script nomodule async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.js"></script>

<form id="form" method="GET">
   <div>
      <what3words-autosuggest api_key="YOUR-API-KEY">
        <input type="text" />
      </what3words-autosuggest>
   </div>
</form>
Copied

Step by Step

1
2

Add component

Installation

The component can be added to static HTML pages by including the what3words.js script on each page of your site that you would like to use the component on.
You could add the what3words API key as a parameter to what3words.js script but we recommend adding the API key as an attribute to the component element instead.

Alternatively, if you are using NPM within your site you can consume one of our packages for your framework.

<script type="module" async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.esm.js"></script>
<script nomodule async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.js"></script>
Copied

Versioning

The AutoSuggest Component is versioned to allow for updates and bug fixes. If installing using HTML we recommend using @4-latest for the development version of your integrations to specify that the latest version of the current major version is loaded. This will ensure that the component is loaded without any breaking changes but receives the benefits of bug fixes and new features.

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.2.2. A log of versions can be found here.

<script type="module" async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.esm.js"></script>
<script nomodule async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.js"></script>
Copied

Extending an input with AutoSuggest functionality

The what3words AutoSuggest Component is a container tag that wraps around an input element. You can either extend an existing input that is to be used as a what3words field or add a new one and wrap the what3words autosuggest container tags around the input.
We recommend specifying the what3words API key as an attribute to the AutoSuggest Component container. You should now replace YOUR-API-KEY with your what3words API key.

<what3words-autosuggest api_key="YOUR-API-KEY">
  <input type="text" />
</what3words-autosuggest>
Copied

You will also need to add an import line to our package if you are using NPM. Adding a label and placeholder as well as making the field optional is recommended particularly when used as part of an input field for a checkout page.

<label for="w3w">what3words address (optional):</label>
<what3words-autosuggest api_key="YOUR-API-KEY">
  <input
    id="w3w"
    placeholder="e.g. ///filled.count.soap"
    type="text"
    optional
  />
</what3words-autosuggest>
Copied

Configuring for use with API server

If you run our Enterprise Suite API Server yourself, you may specify the URL to your own server by appending the baseUrl parameter to the script loaded. Using the frameworks you can specify the baseUrl using window.what3words.api.setOptions.

Although we recommend adding the base_url parameter within the AutoSuggest Component container.

<script type="module" async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.esm.js"></script>
<script nomodule async src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.js?baseUrl=https://example.com/v3"></script>
Copied

Add Strict mode

You can now add strict=false or just strict if you want it to be true (which is the default) to the AutoSuggest Component which allows for non-3wa-like strings to be accepted and the component will not remove the value. It will emit the value_invalid event as it normally does, but the value is not removed and can be used to trigger another integration, such as Google Places API, which the map component does. This way you can now use the autosuggest component with an existing field rather than having to have a dedicated field on your form.

Customise Suggestions (alpha build)

If you are using our new alpha build of the AutoSuggest Component (4.1.0-alpha.12) you can also push your own suggestions to the AutoSuggest Component using the option attribute or programmatically updating this with JavaScript as is shown in the example below. This is currently available through the React and Vue wrappers.

import { What3wordsAutosuggest } from "@what3words/react-components";
import { createRef, useEffect } from "react";
import "./styles.css";

export default function App() {
  const ref = createRef();

  useEffect(() => {
    ref.current.addEventListener("value_invalid", () => {
      const options = [
        {
          value: "Street A",
          id: "street-a",
          description: "Some village",
          distance: {
            value: 10,
            units: "km"
          }
        },
        {
          value: "Street B",
          id: "street-b",
          description: "Some town",
          distance: {
            value: 30,
            units: "km"
          }
        },
        {
          value: "Street C",
          id: "street-c",
          description: "Some city",
          distance: {
            value: 90,
            units: "metres"
          }
        }
      ];
      ref.current.options = options;
    });
    return () =>
      ref.current.removeEventListener("value_invalid", () => {
        console.log("here");
      });
  }, [ref]);

  return (
    <What3wordsAutosuggest ref={ref} api_key="YOUR-API-KEY">
      <input type="text" />
    </What3wordsAutosuggest>
  );
}
Copied
3

Styling component

By default, the JavaScript AutoSuggest Component will load with the what3words predefined style. Whether you have an e-commerce store or a web application, you can match the style of your own site by overriding:

  • CSS class attribute of the Input;
  • variant attribute of the component;
  • what3words address suggestions provided by the component.

Override CSS class

The Input element attributes can be overridden by specifying new CSS values for classes used by the component. For example, you can give the input a class="input-field" and then use CSS to style as it is shown in our example.

Note: recommended using with the variant="inherit" component attribute for the JavaScript AutoSuggest component to inherit the style from a CSS class to match other inputs on your site.

Please visit this interactive code sample to quickly and easily use this solution.

<style>
  .input-field {
    width: 100%;
    font-size: 16px;
    border-width: 0px;
    border-color: #000000;
    background-color: #ffffff;
    color: #000000;
    border-style: outset;
    border-radius: 0px;
    box-shadow: 0px 0px 5px rgba(66, 66, 66, 0.75);
    margin-top: 5px;
    outline: none;
  }
</style>
Copied

Use Inherit variant

We strongly recommend that if you have your own styling set up in your site for other input elements, that you use the component’s variant="inherit" attribute. This attribute removes the default styling, which allows you to easily modify the input style used by the component to match the others on your form.

Note: variant="inherit" attribute should be applied to the component as it shown below.

Please visit this interactive code sample to quickly and easily use this solution

Styling Input

<what3words-autosuggest api_key="YOUR-API-KEY" variant="inherit">
  <input
    type="text"
    id="what3words"
    name="what3words"
    class="input-field"
    optional
  />
</what3words-autosuggest>
Copied

Override what3words address suggestions

The what3words address suggestions and error message used by the component are unaffected by the variant attribute to ensure that the layout of the suggestions is optimal. It is, however, possible to override the style of the what3words address suggestions provided by the component too if desired using CSS overrides to match the styling of your own site.

Please visit this interactive code sample to quickly and easily use this solution

Override the style of the Dropdown

<style>
  .what3words-autosuggest-item {
    background: #ebebeb !important;
    padding: 0px !important;
    box-shadow: none !important;
  }
  .what3words-autosuggest-item .match {
    background: #fcfcfc !important;
    box-shadow: none !important;
  }
  .what3words-autosuggest-item:hover {
    background: #f9f9f9 !important;
    box-shadow: none !important;
  }
  .what3words-autosuggest-item .active,
  .what3words-autosuggest-item:active {
    background: #fc9fc9 !important;
    box-shadow: none !important;
  }
  .what3words-autosuggest-address {
    height: auto !important;
    font-weight: inherit !important;
    font-size: inherit !important;
    line-height: inherit !important;
    color: inherit !important;
  }
  .what3words-autosuggest-address > .what3words-autosuggest-words {
    width: auto !important;
    white-space: inherit !important;
    overflow: inherit !important;
    text-overflow: inherit !important;
  }
  .what3words-autosuggest-nearest-place {
    padding: 0px 0px 0px 18px !important;
  }
  .what3words-autosuggest-nearest-place-text {
  }
  .what3words-autosuggest-nearest-place-text > div:first-child {
    font-size: inherit !important;
    line-height: inherit !important;
    color: inherit !important;
    text-overflow: inherit !important;
  }
  .what3words-autosuggest-nearest-place-distance {
    font-weight: inherit !important;
    font-size: inherit !important;
    line-height: inherit !important;
  }
  .what3words-autosuggest-error-wrapper {
    z-index: inherit !important;
  }
  .what3words-autosuggest-error {
    top: 0px !important;
    border: 0px !important;
    background: #555 !important;
  }
  .what3words-autosuggest-message {
    padding: 0px !important;
    color: inherit !important;
    font-size: inherit !important;
    line-height: inherit !important;
  }
</style>
Copied
4

Localising component

Supported languages

The AutoSuggest Component will accept any 3 word address in any language supported by the what3words API. It can also be added to a site using a right to left language as long as the HTML direction has been set, for example:

<html dir="rtl" lang="ar">
Copied

Localising errors

The error message displayed by the component if a valid 3 word address has not been added can be changed to support location. This can be changed using the attribute error_message:

<what3words-autosuggest api_key="YOUR-API-KEY" invalid_address_error_message="Aucune adresse trouvée">
  <input type="text" />
</what3words-autosuggest>
Copied

Country clipping

In order to refine the suggestions supplied to a user we recommend using country clipping where appropriate. If, for example, the component is to be used on a checkout page then country clipping can be specified using the clip_to_country attribute for the delivery country to ensure that only suggestions are shown in that country and closer matches are displayed. Multiple countries can be specified comma-separated.

<what3words-autosuggest api_key="YOUR-API-KEY" clip_to_country="GB">
  <input type="text" />
</what3words-autosuggest>
Copied

Focus

In addition to country clipping, it is also possible to add focus to results using the autosuggest_focus attribute. The focus should be supplied as a lat, long, usually the user’s location from the GPS on their device. Supplying focus will ensure that suggestions displayed to the user are biased to their location.

<what3words-autosuggest api_key="YOUR-API-KEY" autosuggest_focus="51.1,2.0">
  <input type="text" />
</what3words-autosuggest>
Copied
5

Attributes

Component script parameters

ParameterTypeDescription
keyStringAn API key is required for the component to function correctly. Example: key=Your-API-Key
baseUrlStringThe component can be used with an Enterprise Suite API Server instance by using baseUrl. Example: baseUrl=https://example.com/v3
callbackStringAllows for a callback to be fired once the component has loaded. This should be the function name to be fired. Example: callback=initMap
headersStringEnterprise API Server only - Allows for custom headers to be passed through in requests.

Recommended input element attributes

AttributeTypeDescription
nameStringStandard CSS name. Example: name="what3words"
idStringStandard CSS input ID. If not specified then one will be added by our component. Example: id="what3words"
classStringStandard CSS class - use with the variant=inherit attribute to apply this class to the input element of the component. Example: class="input-field"
valueStringSets the initial value of the input element. We recommend always including the /// before the 3 word address. Example: value="///filled.count.soap"
placeholderStringPlaceholder text to display. We recommend keeping the placeholder as a 3 word address proceeded with "e.g." Example: placeholder="e.g ///filled.count.soap"

Component attributes

AttributeTypeDescription
api_keyStringYour what3words API Key can be specified as an attribute to the component. Example: api_key="Your-API-Key"
variantStringVariant attribute allows for a different variant style to be applied to the input element. variant=inherit allows for the component to inherit the style from a CSS class to match other inputs on a site. A class should be specified on the input in conjunction with variant=inherit. Example: variant="inherit"
invalid_address_error_messageStringOverwrites the error message with a custom value. Example value:"You have entered an invalid address"
languageStringAllows you to add a preferred suggestion fallback language. Only used when input value language cannot be determined. Example: language="EN"
autosuggest_focus StringComma separated lat/lng of a point to focus on AutoSuggest results on. This is useful to focus results on a users location. Example value: autosuggest_focus="51.521251,-0.203586"
n_focus_resultsNumberThe number of AutoSuggest results to apply the focus to. Example: n_focus_results="2"
clip_to_countryStringRestrict suggestions to a given country or comma separated list of countries. Example: clip_to_country="GB,US"
clip_to_bounding_boxStringRestrict suggestions to a bounding box specified using co-ordinates. Example: clip_to_bounding_box="51.521,-0.343,52.6,2.3324"
clip_to_circleStringRestrict suggestions to a circle, specified by lat,lng,kilometres, where kilometres is the radius of the circle. Example: clip_to_circle="51.521251,-0.203586,2"
clip_to_polygonStringRestrict suggestions to a polygon, specified by a comma-separated list of lat,lng pairs. The polygon should be closed, i.e. the first element should be repeated as the last element; also the list should contain at least 4 entries. The API is currently limited to accepting up to 25 pairs. Example: clip_to_polygon="51.521,-0.343,52.6,2.3324,54.234,8.343,51.521,-0.343"
return_coordinatesBooleanMakes an additional call to the what3words API to obtain the coordinates for the selected 3 word address. Note this will use a convert-to-coordinates call whereas without this property only AutoSuggest API calls are made. Example: return_coordinates=true
6

Events

EventDescription
value_changedFired when the value entered into the input changes
value_validFired when a valid 3 word address has been selected from the suggestions
value_invalidFires when input value is not a valid 3 word address
selected_suggestionFires when a suggestion is selected from the dropdown.
suggestions_changedFires when the suggestions displayed in the dropdown change
coordinates_changedOnly when return_coordinates attribute has been enabled. Fires when coordinates change when a new valid 3 word address is selected.

Listening for events

Using an event listener, it is possible to fire other functionality in a site when something changes in the AutoSuggest Component. For example, it is possible to listen for when a valid 3 word address has been entered and update another element in the page or to listen for when new coordinates have been returned and pan/zoom a map to the location.

const autosuggest = document.getElementById("what3words");
autosuggest.addEventListener(
  "selected_suggestion",
  ({
    detail: {
      suggestion: { words }
    }
  }) => {
    console.log("Suggestion selected");
  }
);
Copied
7

Troubleshooting

If you are facing issues with installing the @what3words/angular-components library in your Angular 17 project that is due to a change in how angular projects are built (moving away from babel in v15 to vite in v17) and means the what3words Angular component isn’t successfully imported into Angular 17 projects.
We recommend to:

  1. Update the angular.json file to downgrade the builder from @angular-devkit/build-angular:application to @angular-devkit/build-angular:browser.
  2. Install the @what3words/javascript-components web component library (the @what3words/angular-components won’t work)
  3. Run the src/main.ts file with the web component loader from the @what3words/javascript-components library

Reverting to the legacy angular builder shouldn’t have any downstream impact on your application, as it’s not a breaking change. For now, the @what3words/angular-components doesn’t work in either configuration and we’ll continue to look into this.

Below is a working sample to still be able to use our what3words components in your Angular 17 projects.

WebsiteAdd a 3 word address input fieldAngularJavaScriptReactSalesforceVue

Related tutorials