AutoSuggest jQuery Plugin

Introduction

The what3words AutoSuggest jQuery plugin provides a component to allow the easy capture of 3 word addresses on your website, with the 3 word address validation. The plugin can be obtained from GitHub

The plugin provides a simple way to get started using AutoSuggest on your website. It has been designed to be used when you want a user to input a 3 word address in a form field. Based on a full or partial address, it returns a list of the most relevant 3 word address candidates. Corrections are provided for input errors.

This example demonstrates integrating the what3words AutoSuggest jQuery plugin with Google Maps. Enter a three word address into the search box, select an address from the dropdown, and the map will automatically place a marker on that location.

Sample code

					
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>what3words JQuery Plugin</title>
    <link rel="icon" type="image/png" sizes="32x32" href="https://map.what3words.com/assets/icons/favicon-32x32.png">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/what3words/jquery-plugin-w3w-autosuggest@v1.5.3/dist/css/jquery.w3w-autosuggest-plugin.bundle.css">
    
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/what3words/jquery-plugin-w3w-autosuggest@v1.5.3/dist/js/jquery.w3w-autosuggest-plugin.bundle.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY"></script>
    <script>
      var W3W_KEY = 'YOUR_W3W_API_KEY';
    </script>     

    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
        font-size: 10px;
      }

      /* Overlay the what3words autosuggest widget over the Google Map */
      .searchWrapper {
        position: absolute;
        top: 0;
        left: 300px;
        right: 50px;
        width: auto;
        margin: 10px 0;
        z-index: 99;
      }

      .searchSuggest {
        display: inline-block;
        width: 350px;
        max-width: 100%;
        position: absolute;
        left: 50%;
        margin-left: -300px;
        transform: translate(-50px, 0);
      }
    </style>
  </head>
  <body>
    <!-- Create an input element which will become the search box -->
    <div class="searchWrapper">
      <div class="searchSuggest">
        <input id="twa-input" class="w3w-address-field" type="text" >
      </div>
    </div>

    <div id="map"></div>

    <script>
      // This example adds a search box to a map, using the what3words Autocomplete
      // feature. People can enter a three word address. The search box will return a
      // pick list containing a list of suggestions based on the address entered.

      // Create the Autosuggest widget and link it to the UI element.
      $('#twa-input').w3wAddress({
        key: W3W_KEY,
        results: 5,
        lang: 'en'
      });

      // Create the Google Map
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 51.52086, lng: -0.195499},
        zoom: 13,
        mapTypeId: 'roadmap'
      });

      // Add the what3words grid to the Google Map data layer once the desired zoom level is meet
      map.addListener('bounds_changed', function() {
        const zoom = map.getZoom();
        const loadFeatures = zoom > 17;

        if (loadFeatures) { // Zoom level is high enough
          var ne = map.getBounds().getNorthEast();
          var sw = map.getBounds().getSouthWest();

          // Call the what3words Grid API to obtain the grid squares within the current visble bounding box
          fetch(`https://api.what3words.com/v2/grid?bbox=${ne.lat()},${ne.lng()},${sw.lat()},${sw.lng()}&format=geojson&key=${W3W_KEY}`)
            .then(response => response.json())
            .then(value => {
              if (value.coordinates) {
                // Convert the GeoJSON returned from the what3words Grid API into GeoJSON compatable with Google Maps API
                var grid = {
                  "type": "Feature",
                };
                grid["geometry"] = value;

                // Add the grid data to the Google Maps data layer
                map.data.addGeoJson(grid);
              }
            });
        }
    
        // Set the grid display style
        map.data.setStyle({
          visible: loadFeatures,
          strokeColor: '#777',
          strokeWeight: 0.5,
        });
      });

      var markers = []; 
      // Clear any three word address currently in the search box if the user clicks out onto the map
      $('#twa-input').on('focusout',function(e) {
        $(this).val('');
      });

      // Listen for the event fired when the user selects a three word address and retrieve
      // more details for that location.
      $('#twa-input').on('focusin',function(e) {
        if ($(this).val() !== '') {
          // Call the what3words Forward API to obtain the latitude and longitude of the three word
          // address provided
          fetch(`https://api.what3words.com/v2/forward?addr=${$(this).val()}&key=${W3W_KEY}`)
            .then(response => response.json())
            .then(value => {
              if (value.geometry) {
                // Clear out the old markers.
                markers.forEach(function(marker) {
                  marker.setMap(null);
                });
                markers = [];

                var latLng = {lat: value.geometry.lat, lng: value.geometry.lng};

                // Create a marker for the location
                var marker = new google.maps.Marker({
                  position: latLng,
                  map: map,
                  title: $(this).val(),
                  icon: 'https://map.what3words.com/images/marker-18.png'
                });
                markers.push(marker);

                // Center the map on that location, and zoom in on it to display the grid
                map.setCenter(latLng);
                map.setZoom(20);
              }
            });
        }
      });

    </script>
  </body>
</html>					
				

Usage

The sample also demonstrates integrating the what3words grid into Google Maps by making use of the what3words API grid method.

You will need a what3words API key, which should replace the YOUR_W3W_API_KEY placeholder. If you don't already have an API key, you can obtain one by registering for an account.

To make use of the Google Map integration, you will also need a Google API key, which should replace the YOUR_GOOGLE_API_KEY placeholder.