Autosuggest Component (Mapbox)

A component taken from the what3words JavaScript Wrapper.

The JavaScript API wrapper provides components to make using the what3words API even easier. In this tutorial we will go through using the autosuggest component in combination with a Mapbox. We will add the search field using the component and then respond to its select event to place a pin on the map at the inputted location.

Step 1: Obtain an API key

Sign up to obtain your free API key.

Step 2: Installation

To load the what3words JavaScript API, use a script tag like the one in the following example:

<script src="https://assets.what3words.com/sdk/v3/what3words.js?key=YOUR_API_KEY"></script>

The URL contained in the script tag is the location of a JavaScript file that loads everything you need for using the what3words JavaScript API.

The key parameter contains your application's API key. Sign up to obtain your free API key.

Step 3: Usage

Using the autosuggest component

In one line you can have an input box which will call the what3words autosuggest API endpoint.

<what3words-autosuggest/>

Try it here:

There are a number of ways you can configure the autosuggest component to better suite your usecase, including clipping to country and custom validation errors.

For more on the autosuggest component see the what3words Autosuggest JavaScript Component.

Loading a map using Mapbox

You'll need access to the Mapbox API using your own API key.

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.js'></script>
<script src="https://assets.what3words.com/sdk/v3/what3words.js?key=YOUR_API_KEY"></script> 
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.css' rel='stylesheet' />

Place the map on the page, centered at a location of your chosing.

<div id='map'>
mapboxgl.accessToken = YOUR_MAPBOX_ACCESS_TOKEN;
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v9',
  center: [-0.195499, 51.52086],
  zoom: 12
});

Set the navigation contols.

var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'bottom-right');

Position the component on the map

Determine the position of the component on the map.

<style>
     #autosuggest {
     position: absolute;
     top: 10px;
     left: 10px;
     z-index: 9999;
     }
     #wrapper {
     position: relative;
     height: 100%;
     }
     #map {
     height: 100%;
     } 
     html, body {
     height: 100%;
     margin: 0;
     padding: 0;
     font-size: 10px;
     }
     .marker {
     background-image: url('https://what3words.com/map/images/marker-18.png');
     background-size: cover;
     width: 50px;
     height: 50px;
     border-radius: 50%;
     cursor: pointer;
     } 
</style>

Tie the component to the styling.

<div id="wrapper">
   <div id="autosuggest">
      <what3words-autosuggest id="autosuggest"/>
   </div>
</div>

Listen for the select event

Here we use an event listener to pick up when a user selects a three word address from the listed suggestions for their input. Here we output information to console for debugging purposes.

const input = document.getElementById("autosuggest");
  input.addEventListener("select", (value) => {
    console.log("[EVENT:select]", value.detail);
  });
});

Use convert to coordinates to get the lat/lng of the address.

With the what3words API we can jump between the three word address and the coordinates that relate to it easily. Here we call the api with the three word address selected by the user.

what3words.api.convertToCoordinates(value.detail).then(function(response) {
    console.log("[convertToCoordinates]", response);
});

Use to coordinates gained for the conver to coordinates API call to place a pin on the map and focus on it

Now we have our coordinates we can place a what3words custom marker for our selected three word address on our map and focus the map on this location.

response.features.forEach(function (marker) {
// clear existing markers
markers.forEach(function (marker) {
  marker.remove();
});
markers = [];

// create a HTML element for the marker
var el = document.createElement('div');
el.className = 'marker';  

// make a marker and add to the map
var mapMarker = new mapboxgl.Marker(el)
  .setLngLat(marker.geometry.coordinates)
  .addTo(map);

markers.push(mapMarker);
map.jumpTo({
  center: marker.geometry.coordinates,
  zoom: 19
});

Step 4: Putting It All Together

The example below takes the concepts described above, and turns some of them into a complete example. Here we have a autosuggest component place on a map, where we are listening for the select event. We are then using the what3words JavaScript Wrapper's convert to coordinates functionality to get the coordinates for that address. With those coordinates we then refocus the map and drop a pin on the location selected.

<html>
   <head>
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
      <meta charset="utf-8">
      <title>what3words autosuggest component on mapbox map</title>
      <script src="https://assets.what3words.com/sdk/v3/what3words.js?key=YOUR_API_KEY"></script>
      <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.js'></script>
      <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.css' rel='stylesheet' />
      <style>
         #autosuggest {
         position: absolute;
         top: 10px;
         left: 10px;
         z-index: 9999;
         }
         #wrapper {
         position: relative;
         height: 100%;
         }
         #map {
         height: 100%;
         } 
         html, body {
         height: 100%;
         margin: 0;
         padding: 0;
         font-size: 10px;
         }
         .marker {
         background-image: url('https://what3words.com/map/images/marker-18.png');
         background-size: cover;
         width: 50px;
         height: 50px;
         border-radius: 50%;
         cursor: pointer;
         } 
      </style>
   </head>
   <body>
      <div id="wrapper">
         <div id="autosuggest">
            <what3words-autosuggest id="suggestComponenet"/>
         </div>
         <div id="map"></div>
      </div>
      <script>
         mapboxgl.accessToken = 'YOUR_MAPBOX_API_KEY';
         var map = new mapboxgl.Map({
           container: 'map',
           style: 'mapbox://styles/mapbox/streets-v9',
           center: [-0.195499, 51.52086],
           zoom: 12
         });
         
         var nav = new mapboxgl.NavigationControl();
         map.addControl(nav, 'bottom-right');
         var markers = [];
         
         const input = document.getElementById("suggestComponenet");
         input.addEventListener("select", (value) => {
         
           what3words.api.convertToCoordinatesGeoJson(value.detail).then(function (response) {
             console.log("[convertToCoordinates]", response);
             response.features.forEach(function (marker) {
               markers.forEach(function (marker) {
                 marker.remove();
               });
               markers = [];
         
               // create a HTML element for each feature
               var el = document.createElement('div');
               el.className = 'marker';  
         
               // make a marker for each feature and add to the map
               var mapMarker = new mapboxgl.Marker(el)
                 .setLngLat(marker.geometry.coordinates)
                 .addTo(map);
         
               markers.push(mapMarker);
               map.jumpTo({
                 center: marker.geometry.coordinates,
                 zoom: 19
               });
             });
           });
         });
      </script>
   </body>
</html>