All tutorials
Combining the what3words.js AutoSuggest Component with a Google Map
The what3words 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 Google 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.
You will also need to sign up for a Google Maps developer account and be able to view other Google Maps tutorials at https://developers.google.com/maps/documentation/javascript/tutorial.
We also have tutorials demonstrating its use with both Mapbox and LeafletJS.
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 (Google Map)</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 JS library for the Google Maps API and the JavaScript library for what3words API. You’ll need access to the Google Maps API using your own Google Maps API key.
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> ... // google js library (replace Google API Key) <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY"></script> // 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> ... </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.
<script> function initW3w(what3words) { ... // Create the Google Map const map = new google.maps.Map(document.getElementById('map'), { center: {lat: 51.52086, lng: -0.195499}, zoom: 13, mapTypeId: 'roadmap' }); } </script>
Determine the position of the component on the map.
<style> #autosuggest { position: absolute; top: 50px; left: 9px; z-index: 9999; } #wrapper { position: relative; height: 100%; } #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; font-size: 10px; } </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.
The code snippet below shows 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 to 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: words, format: "geojson" }) .then(function (response) { console.log("[convertToCoordinates]", response); }); }); }
Now that the coordinates of the what3words address are retrieved from the above call to the what3words API, users can place a simple map marker on the map and centre the map on its location.
<script> function initW3w(what3words){ ... // save current map markers in a list (as global variable) let markers = []; const autosuggest = document.getElementById("autosuggest"); autosuggest.addEventListener("selected_suggestion", (value) => { // console.log("[EVENT:select]", value.detail.suggestion.words); let words = value.detail.suggestion.words; // Call the what3words convert to coordinates API to obtain the latitude and longitude of the three word address provided what3words.api.convertToCoordinates({words}).then((response) => { console.log("[convertToCoordinates]", response); if (response.coordinates) { // Clear out the old markers. markers.forEach((marker) => { marker.setMap(null); }); markers = []; let latLng = { lat: response.coordinates.lat, lng: response.coordinates.lng }; // Create a marker for the location let marker = new google.maps.Marker({ position: latLng, map: map, title: words, icon: 'https://map.what3words.com/map/marker.png' }); markers.push(marker); // Center the map on that location, and zoom in on it map.setCenter(latLng); map.setZoom(20); } }); }); } </script>
The example below takes the concepts described above 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" src="https://cdn.what3words.com/javascript-components@4.2.2/dist/what3words/what3words.esm.js" ></script> <script nomodule 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.w3w // and set the callback function for it window.w3w = { callback: "initW3w" }; </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY"></script> <style> #autosuggest { position: absolute; top: 9px; left: 200px; z-index: 100; } #wrapper { position: relative; height: 100%; } #map { height: 400px; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; font-size: 14px; } </style> <title>Autosuggest Component (Google Maps)</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){ //pass your what3words API key to make calls to the what3words API what3words.api.setApiKey("YOUR-API-KEY"); // Create the Google Map const map = new google.maps.Map(document.getElementById('map'), { center: {lat: 51.52086, lng: -0.195499}, zoom: 13, mapTypeId: 'roadmap' }); let markers = []; const autosuggest = document.getElementById("autosuggest"); autosuggest.addEventListener("selected_suggestion", (value) => { console.log("[EVENT:select]", value.detail.suggestion.words); let words = value.detail.suggestion.words; // Call the what3words convert to coordinates API to obtain the latitude and longitude of the three word address provided what3words.api.convertToCoordinates({words}).then((response) => { console.log("[convertToCoordinates]", response); if (response.coordinates) { // Clear out the old markers. markers.forEach((marker) => { marker.setMap(null); }); markers = []; let latLng = { lat: response.coordinates.lat, lng: response.coordinates.lng }; // Create a marker for the location let marker = new google.maps.Marker({ position: latLng, map: map, title: words, icon: 'https://map.what3words.com/map/marker.png' }); markers.push(marker); // Center the map on that location, and zoom in on it map.setCenter(latLng); map.setZoom(20); } }); }); } </script> </html>