Address Autosuggest with HERE

by sainap

HTML

<html>
    <head>
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      <link rel="stylesheet" href="style.css">
      <script src="https://js.api.here.com/v3/3.1/mapsjs-core.js"
      type="text/javascript" charset="utf-8"></script>
      <script src="https://js.api.here.com/v3/3.1/mapsjs-service.js"
      type="text/javascript" charset="utf-8"></script>

    </head>
    <body>
      <div id="pac-container">
        <h2>Address Autosuggest</h2>

        <input list="prediction-list" id="address-input" type="text"
               placeholder="Enter a location" autocomplete="off">

        <datalist id="prediction-list">
        </datalist>

        <div id="result"></div>
      </div>
      
    </body>
  </html>

CSS

body {
  background: linear-gradient(230deg, #a24bcf, #4b79cf, #4bc5cf);
  font-family: Arial;
}

#pac-container {
  width: 80%;
  height: 90%;
  position: absolute;
  left: 1em;
  top: 1em;
  background-color: white;
}

#pac-container h2 {
  /* margin-left: 1em; */
  margin-block-start: 0px;
  margin-block-end: 0px;
  padding: 1em;
  background-color: rgb(0, 175, 170, 0.2);
}

#pac-container input {
  margin-left: 1.8em;
  margin-top: 1em;
  width: 80%;
  padding: 12px 20px;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  background-color: #f2f2f2;
}

#pac-container input:hover {
  border-color: #0986b6;

}

JavaScript

function init() {
  const result = document.getElementById('result');

  // Initialize the platform object:
  const platform = new H.service.Platform({
    apikey: '0jhvJzLcnnAz9MoO4PdII2wXZpzYb2rbn1F99aq3MOE',
  });

  // Get an instance of the geocoding service:
  const service = platform.getSearchService();

  const input = document.getElementById('address-input');
  const options = document.getElementById('prediction-list');

  input.addEventListener('keyup', function displayResults(e) {
		if (e.which > 90 || e.which < 48) {
        return;
    } 

    const soFar = this.value;
    getPredctions(soFar)
      .then((result) => {
 	    let predictions = result.items;
        removeAllChildNodes(options);
        predictions = result.items;
        predictions.slice(-5).forEach((prediction) => {
          const newOption = document.createElement('option');

          const label = (typeof prediction.address === 'undefined') ? prediction.title : prediction.address.label;
          newOption.value = label;
          options.appendChild(newOption);
        });
      });
  });

  function getPredctions(str) {
    return service.autosuggest({
      // Search query
      q: str,
      // Center of the search context
      at: '47.657263,-122.306522',
    });
  }

  function removeAllChildNodes(parent) {
    while (parent.firstChild) {
      parent.removeChild(parent.firstChild);
    }
  }
}

window.addEventListener('load', init);