All tutorials

Using the Web Map Component

intermediate

Introduction

The easiest way to add what3words to your technology is to use one of our components. We have several components available for JavaScript, iOS, and Android which require minimal development to integrate. They can also be used in Angular, React, or Vue projects as framework-native components. Find out how else you can utilise the what3words API using JavaScript by taking a look at the functions in the what3words JavaScript API Wrapper. The web map component declares a custom DOM element that allows for a quick and simple way of adding the what3words grid on top of Google Maps, displaying the what3words address and marker on the map for a selected three word address.

You can optionally integrate the AutoSuggest Component with the map too and it will enable searching of 3 word addresses or traditional addresses and traverses the map to the selected three 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 Map Component can be added to a website either for static pages via our CDN or using NPM as part of your project dependencies.

Follow the steps below to select your chosen technology to find out how you can add the what3words map component to your project.

Follow the steps below to select your chosen technology to find out how you can add the what3words map component to your project.

Quickstart

The Web Map Component requires just a few lines of code to be added to a site to create a map with what3words functionality. Replace YOUR-API-KEY with your what3words API key and the YOUR-GOOGLE-API-KEY with your Google Maps API key.

<head>
<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> 

<style>
html, body {
  margin: 0px;
  height: 100%;
}
#map-container {
  width: 100vw;
  height: 100vh;
}
#search-container {
  margin: 10px 0 0 10px;
}
#search-input {
  width: 300px;
}
#current-location-container {
  margin: 0 10px 10px 0;
}
</style>

</head>
<body>
  <what3words-map
    id="w3w-map"
    api_key="YOUR-API-KEY"
    map_api_key="YOUR-GOOGLE-MAP-API-KEY"
    disable_default_ui
    fullscreen_control
    map_type_control
    zoom_control
    current_location_control_position="9"
    fullscreen_control_position="3"
    search_control_position="2"
    words="filled.count.soap"
  >
    <div slot="map" id="map-container"></div>
    <div slot="search-control" id="search-container">
    <what3words-autosuggest>
        <input
            id="search-input"
            type="text"
            placeholder="Find your address"
            autocomplete="off"
        />
        </what3words-autosuggest>
    </div>
    <div slot="current-location-control" id="current-location-container">
        <button>Current Location</button>
    </div>
  </what3words-map>
</body>
Copied

Step by Step

1Get API key
Signup to create key
2Get Google API key

You also will need to get a Google API key for your chosen map provider (only Google is currently supported).

Note:
In console.cloud.google.com you should select: API and services > Enabled APIs and services
Search for places API and then select and enable it.

3Add Map Component

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. A notable limitation imposed by Google Maps restricts the number of maps that can be rendered on any single page (details are provided in the Troubleshooting section).

You will need to replace <YOUR-API-KEY> with your what3words API key. This will attach the what3words API to the window accessible via window.what3words. This parameter is only required if you need the latter functionality. Alternatively, if you are using a package manager (e.g. npm) within your site you can consume one of our packages for your framework.

<script type="module" src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.esm.js?"></script>
<script nomodule src="https://cdn.what3words.com/javascript-components@4.8.0/dist/what3words/what3words.js?key=<YOUR-API-KEY>" defer></script>
Copied

Add Current Location Functionality (Optional)

To enable your customers to choose their current location and discover their three word address, you will need to add a current-location-control slot container with a child button as a sibling to the search-control slot. This can be styled using CSS with its position on the map canvas controlled by the current_location_control_position What3Words Map Component property. A simple implementation is shown below:

...
<div slot="search-control" id="search-container">
  <what3words-autosuggest>
    <input id="search-input" type="text" placeholder="Find your address" autocomplete="off">
  </what3words-autosuggest>
</div>
<div slot="current-location-control" id="current-location-container">
  <button>Current Location</button>
</div>
...
Copied

Insert Map Component

Then we will need to wrap the map container and the search box within the what3words Map Component as shown here to display the what3words grid and marker on Google Maps. Notice you will need to add your what3words API key to the api_key parameter and your Google Maps API key to map_api_key parameter.

Note: You will also need to add an import line to our package if you are using npm.

<body>
  <what3words-map
   id="w3w-map"
   api_key="YOUR-API-KEY"
   map_api_key="YOUR-GOOGLE-API-KEY"
  >
  </what3words-map>
</body>
Copied

Define a map container

Add HTML and CSS to create a page with a #map element. The #map is the element that displays the map and its CSS resets any browser settings, so it can consume the full width and height of the browser. Note that we must specifically declare those percentages for <body> and <html> as well.

For the map to display on a web page, we must reserve a spot for it. Commonly, we do this by creating a named <div> element and obtaining a reference to this element in the browser’s document object model (DOM).

<body>
  <what3words-map
   id="w3w-map"
   api_key="YOUR-API-KEY"
   map_api_key="YOUR-GOOGLE-API-KEY"
  >
    
   <div slot="map" id="map"></div>

  </what3words-map>
</body>
Copied

Insert Search field

You could insert a seach box by simply adding a search-control slot within the Map Component. In the search-control slot you can specify your customised search box.

<body>
  <what3words-map
   id="w3w-map"
   api_key="YOUR-API-KEY"
   map_api_key="YOUR-GOOGLE-API-KEY"
  >
    
   <div slot="map" id="map"></div>
   <div slot="search-control">
   // Enter here your customised Search box
   </div>
    
  </what3words-map>
</body>
Copied

Use AutoSuggest Component in the Search field (Optional)

You could also provide a type-ahead search box that includes the what3words Web AutoSuggest Component and the common address from Google Places, you will need to add the following code on your body below the div element that is used as a map container.

Note: This is completly optional. You will also need to add an import line to our AutoSuggest Component package if you are using npm.

<body>
  <what3words-map
   id="w3w-map"
   api_key="YOUR-API-KEY"
   map_api_key="YOUR-GOOGLE-API-KEY"
  >
    
   <div slot="map" id="map"></div>
   <div slot="search-control">
     <what3words-autosuggest>
       <input type="text" placeholder="e.g. ///filled.count.soap" />
     </what3words-autosuggest>
   </div>
    
  </what3words-map>
</body>
Copied

Customise the Map Component

The Map Component can be customised using common Google Maps options and other what3words properties. Here is shown an example of how to add these options and properties together.

<what3words-map
   id="w3w-map"
   api_key="YOUR-API-KEY"
   map_api_key="YOUR-GOOGLE-API-KEY"
   zoom="8"
   selected_zoom="20"
   lng="-0.114637"
   lat="51.454843"
   search_control_position="2"
   map_type_control
   zoom_control
   fullscreen_control
   fullscreen_control_position="3"
   current_location_control_position="9"
   disable_default_ui
   map_type_id="satellite"
   words="filled.count.soap"
 >
...
</what3words-map>
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 adding the base_url parameter to the Map Component.

<what3words-map
   ...
   base_url="https://example.com/v3"
>
...
</what3words-map>
Copied

Styling Map Component

By default, the Web Map Component will load with the what3words predefined map marker icon. You can choose your own icon by adding their URL path to the marker_icon attribute.

<what3words-map
  ...
  marker_icon="./assets/redmarker.png"
>
 ...
</what3words-map>
Copied

Select Map Provider

Our Map Component could support different map service providers, such as Google Maps, Mapbox, Apple Maps, and many more, by adding the property provider to the Map Component. Currently, the only map service provider accepted is Google Maps provider = "google" but in the future will be extended to support mapbox (for MapBox), apple (for Apple Maps) and other map providers.

<what3words-map
   ...
   provider="google"
>
...
</what3words-map>
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 (Optional)

If you are using our AutoSuggest Component in your Search box, with the new alpha build 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
4Attributes

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.

Component Attributes

ParameterTypeDescription
api_keyStringYour what3words API Key can be specified as an attribute to the component. Example: api_key="Your-API-Key"
api_versionStringYou can specify the what3words API version as an attribute to the component. Example: api_version=”v1”
base_urlStringThe component can be used with an Enterprise Suite API Server instance by using base_url. Example: base_url =https://example.com/v3
current_locationBooleanEnables/disables the current location.
current_location_control_position NumberPosition id. Used to specify the position of the current location control on the map.
disable_default_uiBooleanEnables/disables all default UI buttons. May be overridden individually. Does not disable the keyboard controls or the gesture controls.
fullscreen_controlBooleanThe enabled/disabled state of the Fullscreen control.
fullscreen_control_positionNumberPosition Id. Used to specify the position of the control on the map. The default position is RIGHT_TOP
headersStringEnterprise API Server only - Allows for custom headers to be passed through in requests.
languageStringSee https://developers.google.com/maps/faq#languagesupport Allows you to add a preferred suggestion fallback language for google maps. Example: language="EN"
latNumberIt specifies the latitude of an initial position on the map. Example: lat=-34.397.
libraries("drawing" | "geometry" | "localContext" | "places" | "visualization")It loads additional libraries by specifying a libraries parameter in the request, and supplying the name of the library or libraries. You can specify multiple libraries as a comma-separated list. See the full list here: https://developers.google.com/maps/documentation/javascript/libraries.
lngNumberIt specifies the longitude of an initial position on the map. Example: lng=150.644
map_api_key StringA Google Maps API key is required for the component to function correctly.
map_type_controlBooleanThe initial enabled/disabled state of the Map type control.
map_type_control_position NumberPosition id. Used to specify the position of the map type control on the map. Default TOP_RIGHT.
map_type_id"hybrid" | "roadmap" | "satellite" | "terrain"IDs of map types to show in the control.
marker_iconStringYou can use the default marker icon or use your own one [MARKER_SRC]. Example: marker_icon="logo_sample.jpg".
providerStringMap Service provider. Currently it accepts only "google". In the future will be extended to support "mapbox", "apple" and other map service providers.
regionStringA region code of the user's region. The region code accepts a ccTLD ("top-level domain") two-character value. Most ccTLD codes are identical to ISO 3166-1 codes, with some notable exceptions. For example, the United Kingdom's ccTLD is "uk" (.co.uk) while its ISO 3166-1 code is "gb" (technically for the entity of "The United Kingdom of Great Britain and Northern Ireland").
rotate_controlBooleanThe enabled/disabled state of the Rotate control.
rotate_control_positionNumberPosition id. Used to specify the position of the rotate control on the map. The default position is TOP_LEFT.
scale_controlBooleanThe initial enabled/disabled state of the Scale control.
search_control_positionNumberPosition id. Used to specify the position of the search control on the map. The default position is TOP_LEFT.
selected_zoomNumberThe initial what3words Grid zoom level.
street_view_controlBooleanThe initial enabled/disabled state of the Street View Pegman control. This control is part of the default UI, and should be set to false when displaying a map type on which the Street View road overlay should not appear (e.g. a non-Earth map type).
street_view_control_positionNumberPosition id. Used to specify the position of the street view control on the map. The default position is embedded within the navigation (zoom and pan) controls. If this position is empty or the same as that specified in the zoom_control_position, the Street View control will be displayed as part of the navigation controls. Otherwise, it will be displayed separately.
tiltNumberFor vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45.
versionStringGoogle Maps JavaScript API version loaded by the browser. See https://developers.google.com/maps/documentation/javascript/versions.
watch_locationBooleanIt watches your location and the event listener will be triggered every time their location changes.
wordsStringIniital what3words address to be searched and displayed on the map.
zoomNumberThe initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level. Larger zoom values correspond to a higher resolution.
zoom_controlBooleanThe enabled/disabled state of the Zoom control.
zoom_control_positionNumberPosition id. Used to specify the position of the zoom control on the map. The default position is TOP_LEFT. More on the ControlPosition constants on Google Maps:https://developers.google.com/maps/documentation/javascript/reference/control#ControlPosition.
5Events
EventDescription
coordinates_changedFires when coordinates change when a new valid 3 word address is selected. Returns the coordinates of the selected square on the map.
selected_squareFires when a square on the what3words grid has been selected. Returns all details of that selected square.

Listening for events

Using an event listener, it is possible to fire other functionality in a site when something changes in the Map Component. For example, it is possible to listen for when a square on the grid map has been selected by the users or to listen for when new coordinates have been returned and pan/zoom a map to the location.

<script>
  const w3wMap = document.getElementById("w3w-map");
  w3wMap.addEventListener(
    "selected_square",
    console.log("Selected what3words square")
  );
</script>
Copied
6Methods
Method NameResults
clearGridclearGrid(); Parameters: None. Return Value: None. Reset the polilynes of the grid on the map.
getBoundsgetBounds(); Parameters: None. Return Value: LatLngBounds|undefined. Returns the lat/lng bounds of the current viewport [south: number; west: number; north: number; east: number;]. If the map is not yet initialized or center and zoom have not been set then the result is undefined.
getGridgetGrid(); Parameters: None. Return Value: google.maps.Polyline[]. Returns the polylines of the grid on the map.
getLatgetLat(); Parameters: None. Return Value: number|undefined. Returns the latitude of an initial position on the map. If the latitude has not been set then the result is undefined.
getLnggetLng(); Parameters: None. Return Value: number|undefined. Returns the longitude of an initial position on the map. If the longitude has not been set then the result is undefined.
getMapTypeIdgetMapTypeId(); Parameters: None. Return Value: MapTypeId|string|undefined. Returns the MapTypeId of the map.
getZoomgetZoom(); Parameters: None. Return Value: number|undefined. Returns the zoom of the map. If the zoom has not been set then the result is undefined.
panTopanTo(coordinates); Parameters: coordinates: LatLng|LatLngLiteral. The new center latitude/longitude of the map. Return Value: None. Changes the center of the map to the given coordinates. If the change is less than both the width and height of the map, the transition will be smoothly animated.
setApiKeysetApiKey(key); Parameters: key: string. Return Value: None.
setApiVersionsetApiVersion(api_version); Parameters: api_version: ApiVersion. Return Value: None.
setBaseUrlsetBaseUrl(host); Parameters: host: string. Return Value: None
setGridsetGrid(grid); Parameters: grid: any[]. Return Value: None.
setHeaderssetHeaders(value); Parameters: value: string. Enterprise API Server only - Allows for custom headers to be passed through in requests. Return Value: None.
setLatsetLat(lat); Parameters: lat: number. It specifies the latitude of an initial position on the map. Return Value: None.
setLngsetLng(lng); Parameters: lng: number. It specifies the longitude of an initial position on the map. Return Value: None.
setMapTypeIdsetMapTypeId(mapTypeId); Parameters: mapTypeId: MapTypeId|string. Return Value: None.
setOptionssetOptions(options); Parameters: options: MapOptions optional. Return Value: None.
setWordssetWords(words); Parameters: words: string. Initial what3words address to be searched and displayed on the map. Return Value: None. Sets the initial what3words address on the map.
setZoomsetZoom(zoom); Parameters: zoom: number. Larger zoom values correspond to a higher resolution. Return Value: None. Sets the zoom of the map.
7Full Example

The example below takes the concepts described earlier and demonstrates how our JavaScript Map Component can be added to a website as an HTML static page via our CDN.

8Full Example in React

The example below takes the concepts described earlier and demonstrates how our JavaScript Map Component can be added to a website using NPM as part of your project dependencies and React as a framework.

9Full Example in Vue

The example below takes the concepts described earlier and demonstrates how our JavaScript Map Component can be added to a website using NPM as part of your project dependencies and Vue as a framework.

10Full Example in Angular

The example below takes the concepts described earlier and demonstrates how our JavaScript Map Component can be added to a website using NPM as part of your project dependencies and Angular as a framework.

11Full Example in Angular with Routers

The example below takes the concepts described earlier and demonstrates how our JavaScript Map Component can be added to a website using NPM as part of your project dependencies and Angular as a framework.

If you are looking to build Single Page Applications with multiple views and allow navigation between these views you should use this code snippet to add the Angular Router.

12Troubleshooting

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

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

“For Development Purposes Only” on Google Maps

Issue

If you see a “For development purposes only” text over your Google Maps and it’s not loading correctly, there’s an issue with your Google Maps API key. This typically occurs because Google Cloud Billing is not enabled, or a Google Maps API key has not been generated for your organization.

Solution

1. Enable Google Cloud Billing:

  • Go to your Google Cloud Billing settings and ensure billing is enabled.
  • Select your current project at the top left if necessary.

Google requires billing to be enabled if your free trial has ended or if you’ve exceeded the free monthly tier.

2. Generate a Google Maps API Key:

For further assistance, contact Google Cloud support.

Google Maps Loader Error

Issue

If you encounter the following error in your console raised by the Google Maps loader package js-api-loader, it indicates an issue with creating multiple map instances. This error can occur due to:

  • Multiple re-renders with missing/different props passed to the Map component.
  • Attempting to load multiple maps on the same page with different properties.

Solution

This is a known issue that we aim to resolve in future releases. In the meantime, if you need multiple map instances on a single page, ensure you maintain the following properties for every what3words Map component:

  • map_api_key

  • language

  • libraries

  • region

While this workaround is not officially supported, it may help mitigate the issue. For further assistance, please get in touch with support@what3words.com.

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.

WebsiteAdd a 3 word address input fieldDisplay a 3 word addressUse 3 word addresses with a mapUse 3 word addresses within an address searchAngularJavaScriptReactVue

Related tutorials