All tutorials
Combining the what3words.js AutoSuggest Component with a LeafletJS Map
The JavaScript wrapper for the what3words API provides components to make using the what3words API even easier. In this tutorial, we will show you how to use the AutoSuggest component in combination with a LeafletJS map. 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.
LeafletJS is an open source mapping engine. More information on LeafletJS can be found at: https://leafletjs.com/reference-1.5.0.html
We also have tutorials demonstrating its use with both Mapbox and Google Map.
Define an HTML page to create a map that is the full width and height of the web browser window.
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 take the full width and height of the browser.
The <!DOCTYPE html>
tag is not required in CodeSandbox. If you are using a different editor or running the page on a local server, be sure to add this tag to the top of your HTML page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" /> <title>Autosuggest Component (Leaflet)</title> <style> html, body, #map { position: absolute; height: 100%; width: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> </body> </html>
In the <head>
tag, add references to the CSS file and JS library for the LeafletJS API and the JavaScript library for what3words API.
You can also attach the what3words API to the window, which is accessible via window.what3words
, and set a callback function for it, using script
tags like the ones in the following example. Don’t forget to set your what3words API key.
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.
<head> ... // what3words JS library <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> <script> // Attach the what3words API to the window accessible via window.what3words // and set the callback function for it window.w3w={ callback: "initW3w" }; </script> // leaflet JS library <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script> // leaflet CSS library <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> ... </head> <body> ... <script> function initW3w(what3words) { //pass your what3words API key to make calls to the what3words API what3words.api.setApiKey("YOUR-API-KEY"); ... } </script> </body>
Now you can place the map on the page, centered at a location of your choosing. The #map
in the <html>
tag will render the map.
function initW3w(what3words) { ... let map = L.map("map", { zoomControl: false }).setView( [51.520847, -0.195521], 16 ); L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', maxNativeZoom: 19, maxZoom: 25 }).addTo(map); ... }
To Display map navigation controls on the Mapbox map, use addControl
to add zoom and rotation controls to the map.
const nav = new mapboxgl.NavigationControl(); map.addControl(nav, 'bottom-right');
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: 400px; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; font-size: 12px; } </style>
Tie the component to the styling. Ensure you include <div id=”map”></div>
within the wrapper to display the map.
<div id="wrapper"> ... <div id="map"></div> </div>
In a few lines of code, you can have an input box that will call the what3words AutoSuggest API endpoint.
The api_key
parameter contains your application’s API key. Replace YOUR-API-KEY
with your what3words API key to get started.
Sign up to obtain your free API key.
<div id="wrapper"> <what3words-autosuggest id="autosuggest" api_key="YOUR-API-KEY"> <input type="text" /> </what3words-autosuggest> <div id="map"></div> </div>
There are a number of ways you can configure the AutoSuggest component to better suit your use case, including clipping to country and custom validation errors.
For more on the AutoSuggest component see the what3words AutoSuggest JavaScript Component.
On the code snippet below, it is shown how to use an event listener to detect when a user selects a what3words address from the listed suggestions for their input. For debug purposes, it has been added a console log to show how to retrieve the words of the suggestions:
function initW3w(what3words) { ... let words; const autosuggest = document.getElementById("autosuggest"); autosuggest.addEventListener("selected_suggestion", (value) => { let words = value.detail.suggestion.words; // console.log(words); }); ... }
To convert a what3words address to coordinates, users will need to call the what3words API as shown below. They will need to add this code snippet within the autosuggest
event listener.
function initW3w(what3words) { ... let words; const autosuggest = document.getElementById("autosuggest"); autosuggest.addEventListener("selected_suggestion", (value) => { let words = value.detail.suggestion.words; // what3words api call request what3words.api .convertToCoordinates({ words }) .then(function (response) { console.log("[convertToCoordinates]", response); }); }); }
Now we have our coordinates we can place a what3words custom marker for our selected what3words address on our map and focus the map on this location.
<script> function initW3w(what3words) { ... let markers = []; const autosuggest = document.getElementById("autosuggest"); autosuggest.addEventListener("selected_suggestion", (value) => { let words = value.detail.suggestion.words; // Call the what3words Forward API to obtain the latitude and longitude of the what2words address provided what3words.api .convertToCoordinates({ words }) .then(function (response) { if (response.coordinates) { console.log(response); // Clear out the old markers. markers.forEach(function (marker) { marker.remove(); }); markers = []; let marker = L.marker( [response.coordinates.lat, response.coordinates.lng], { icon: w3wIcon } ).addTo(map); // Create a marker for the location markers.push(marker); // Center the map on that location, and zoom in on it to display the grid map.setView( [response.coordinates.lat, response.coordinates.lng], 18 ); } }); }); } </script>
The example below takes the concepts described in the step by step guide and turns some of them into a complete example. Here we have an 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.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <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> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin="" ></script> <script> // Set the callback function for w3w window.w3w = { callback: "initW3w" }; </script> <style> #autosuggest { position: absolute; top: 10px; left: 10px; z-index: 500; } #wrapper { position: relative; height: 100%; } #map { height: 100%; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; font-size: 14px; } </style> <title>Autosuggest Component (Leaflet)</title> </head> <body> <div id="wrapper"> <what3words-autosuggest id="autosuggest" api_key="YOUR-API-KEY"> <input type="text" /> </what3words-autosuggest> <div id="map"></div> </div> <script> function initW3w(what3words) { what3words.api.setApiKey("YOUR-API-KEY"); var w3wIcon = L.icon({ iconUrl: "https://what3words.com/map/marker.png", iconSize: [64, 64], // size of the icon iconAnchor: [25, 59] // point of the icon which will correspond to marker's location }); var map = L.map("map", { zoomControl: false }).setView( [51.520847, -0.195521], 16 ); L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', maxNativeZoom: 19, maxZoom: 25 }).addTo(map); new L.Control.Zoom({ position: "bottomright" }).addTo(map); var markers = []; const autosuggest = document.getElementById("autosuggest"); autosuggest.addEventListener("selected_suggestion", (value) => { let words = value.detail.suggestion.words; // Call the what3words Forward API to obtain the latitude and longitude of the three word address provided what3words.api .convertToCoordinates({ words }) .then(function (response) { if (response.coordinates) { console.log(response); // Clear out the old markers. markers.forEach(function (marker) { marker.remove(); }); markers = []; var marker = L.marker( [response.coordinates.lat, response.coordinates.lng], { icon: w3wIcon } ).addTo(map); // Create a marker for the location markers.push(marker); // Center the map on that location, and zoom in on it to display the grid map.setView( [response.coordinates.lat, response.coordinates.lng], 18 ); } }); }); } </script> </body> </html>