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 it’s use with both Mapbox and Google Map.
You will need a what3words API key to complete this tutorial.
Installation
To load the JavaScript wrapper for the what3words API, use a script
tag like the one in the following example:
<script src="https://assets.what3words.com/sdk/v3.1/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 JavaScript wrapper for the what3words API.
The key
parameter contains your application’s API key. Sign up to obtain your free API key.
Usage
Using the AutoSuggest component
In one line you can have an input box which will call the what3words AutoSuggest API endpoint.
<what3words-autosuggest/>
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.
Loading a map using LeafletJS
You’ll need to give yourself access to the what3words AutoSuggest component and the style and js from LeafletJS
<script src="https://assets.what3words.com/sdk/v3/what3words.js?key=YOUR_API_KEY"></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>
Place the map on the page, centered at a location of your choice.
<div id='map'> 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); });
Set the navigation contols.
var nav = new mapboxgl.NavigationControl(); map.addControl(nav, 'bottom-right');
Position 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.
<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 3 word address from the listed suggestions for their input. Here we output information to console for debugging purposes.
const input = document.getElementById("suggestComponent"); input.addEventListener("select", (value) => { console.log("[EVENT:select]", value.detail); }); });
Use convert to coordinates to get the lat/long of the address.
With the what3words API we can switch between the 3 word address and the coordinates that relate to it easily. Here we call the API with the 3 word address selected by the user.
what3words.api.convertToCoordinates(value.detail).then(function(response) { console.log("[convertToCoordinates]", response); });
Use to coordinates gained for the convert 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 3 word address on our map and focus the map on this location.
if (response.coordinates) { // 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); } });