Using the JavaScript AutoSuggest Component (v4)
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 what3words 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 what3words 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 what3words 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.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"></script> <form id="form" method="GET"> <div> <what3words-autosuggest api_key="YOUR-API-KEY"> <input type="text" /> </what3words-autosuggest> </div> </form>
Step by Step
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.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"></script>
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.8.0
. A log of versions can be found here.
<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"></script>
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>
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>
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.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?baseUrl=https://example.com/v3"></script>
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> ); }
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>
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
<what3words-autosuggest api_key="YOUR-API-KEY" variant="inherit"> <input type="text" id="what3words" name="what3words" class="input-field" optional /> </what3words-autosuggest>
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
<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>
Supported languages
The AutoSuggest Component will accept any what3words 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">
Localising errors
The error message displayed by the component if a valid what3words 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>
Seamless Language Support
The AutoSuggest Component now automatically adapts to your user’s language preferences. Localised parts include the placeholder, error message, and invalid error message. If you specify the language in the HTML (e.g. <html lang="de">
), the component will use that language. If not, it falls back to the browser’s language settings. If the language of the what3words address isn’t specified (e.g. language='es'
), the component will default to the HTML page or browser language.
This uses 2-letter ISO codes or locale codes and defaults to English (en-GB) if an unsupported language is detected. Error handling is improved, providing clear feedback in the console for unsupported languages. The update supports javascript-components@4.3.1
, benefiting React, Vue, and Angular components.
Country clipping
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 as comma-separated.
<what3words-autosuggest api_key="YOUR-API-KEY" clip_to_country="GB"> <input type="text" /> </what3words-autosuggest>
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>
Component script parameters
Parameter | Type | Description |
---|---|---|
key | String | An API key is required for the component to function correctly. Example: key=Your-API-Key |
baseUrl | String | The component can be used with an Enterprise Suite API Server instance by using baseUrl. Example: baseUrl=https://example.com/v3 |
callback | String | Allows for a callback to be fired once the component has loaded. This should be the function name to be fired. Example: callback=initMap |
headers | String | Enterprise API Server only - Allows for custom headers to be passed through in requests. |
Recommended input element attributes
Attribute | Type | Description |
---|---|---|
name | String | Standard CSS name. Example: name="what3words" |
id | String | Standard CSS input ID. If not specified then one will be added by our component. Example: id="what3words" |
class | String | Standard CSS class - use with the variant=inherit attribute to apply this class to the input element of the component. Example: class="input-field" |
value | String | Sets the initial value of the input element. We recommend always including the /// before the what3words address. Example: value="///filled.count.soap" |
placeholder | String | Placeholder text to display. We recommend keeping the placeholder as a what3words address proceeded with "e.g." Example: placeholder="e.g ///filled.count.soap" |
Component attributes
Attribute | Type | Description |
---|---|---|
api_key | String | Your what3words API Key can be specified as an attribute to the component. Example: api_key="Your-API-Key" |
variant | String | Variant 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_message | String | Overwrites the error message with a custom value. Example value:"You have entered an invalid address" |
language | String | Allows you to add a preferred suggestion fallback language. Only used when input value language cannot be determined. Example: language="EN" |
autosuggest_focus | String | Comma 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_results | Number | The number of AutoSuggest results to apply the focus to. Example: n_focus_results="2" |
clip_to_country | String | Restrict suggestions to a given country or comma separated list of countries. Example: clip_to_country="GB,US" |
clip_to_bounding_box | String | Restrict suggestions to a bounding box specified using co-ordinates. Example: clip_to_bounding_box="51.521,-0.343,52.6,2.3324" |
clip_to_circle | String | Restrict 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_polygon | String | Restrict 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_coordinates | Boolean | Makes an additional call to the what3words API to obtain the coordinates for the selected what3words address. Note this will use a convert-to-coordinates call whereas without this property only AutoSuggest API calls are made. Example: return_coordinates=true |
Event | Description |
---|---|
value_changed | Fired when the value entered into the input changes |
value_valid | Fired when a valid what3words address has been selected from the suggestions |
value_invalid | Fires when input value is not a valid what3words address |
selected_suggestion | Fires when a suggestion is selected from the dropdown. |
suggestions_changed | Fires when the suggestions displayed in the dropdown change |
coordinates_changed | Only when return_coordinates attribute has been enabled. Fires when coordinates change when a new valid what3words 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 what3words 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"); } );
If you encounter errors or issues related to convert-to-coordinate, convert-to-3wa and grid-section 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 or API plan does not have access to this feature. Please change your plan at https://accounts.what3words.com/select-plan, or contact support@what3words.com" } }
For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.
Issues with Angular 17 Compatibility
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:
- Update the
angular.json
file to downgrade the builder from@angular-devkit/build-angular:application
to@angular-devkit/build-angular:browser.
- Install the
@what3words/javascript-components
web component library (the@what3words/angular-components
won’t work) - 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.
Please contact support@what3words.com for a working sample to still be able to use our what3words components in your Angular 17 projects.
Vite Compatibility Issue
Our current components do not yet work with Vite due to a known issue with Stencil. A potential fix is expected in a future version upgrade, which we are currently working on. It may take some time before this fix is available and tested. For now, we advise against using Vite. For more details, refer to the GitHub issue.