Tutorials / How to Find Geocoordinates (GPS) using the Autosuggest Feature of the Geocoding and Search API
Last Updated: October 01, 2020

Introduction

Many applications such as vehicle tracking, routing, weather forecasting and more require geocoordinates. The Geocoding and Search API helps find geocoordinates of addresses, places, localities and administrative areas (e.g. city, state and country).

The Geocoding and Search API allows you to do forward geocoding and reverse geocoding. This tutorial focuses on “forward geocoding”. You can learn about reverse geocoding here.

Forward geocoding allows you to find the coordinates from a known address.

In this tutorial, we will show you how you leverage the “Autosuggest” feature of HERE Geocoding and Searching API and build a sample application that receives a street address and then places a marker on a map.

In the map below you will see the final output. Output

To see the final product, click here to view the working map.

Pre-Reqs.

Roadmap

To complete this tutorial, we will follow the general steps below:

  1. Create a basic HERE map.
  2. Add a search box to the map.
  3. Implement the Geocoding and Search API to find the geocoordinates.
  4. Add a marker to the map.

Create a Basic HERE Map

To create a HERE map, follow the steps below:

  • Open your favorite editor.
  • Create an index.html file.
  • Copy the following boilerplate code into the index.html and replace the HERE-API-KEY with your own.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--HERE JS libs-->
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
<!--HERE JS libs-->
<!-- style sheet -->
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- end of style sheet -->
<style>
 .dropdown {
  position: absolute;
  z-index: 99999;
  list-style-type: none;
  width: 360px;
  border: rgb(15, 22, 33);
  list-style: none;
  top: 135px;
}
input{
  z-index: 9999; font-size: 18px;
  font-family: 'Allerta', Helvetica, Arial, sans-serif;
  color: #495057;position: absolute; top: 100px; left: 20px; 
  width: 350px; height: 35px; padding: 5px; margin-left: 17px; 
  margin-top: 7px; border: none;
}
ul{
  list-style: none; background-color: white; padding: 0px;
  margin-left: 29px;
width: 360px;
}
li{
  list-style-type: none;
  height: 12px;
  padding: 12px;
  box-shadow: rgb(158, 202, 237) 0px 0px 4px;
  display: list-item;
  text-align: -webkit-match-parent;
  font-family: 'Allerta', Helvetica, Arial, sans-serif;
  color: #495057;
  }
li:hover {
  background-color: yellowgreen;
}
#list {
  cursor: pointer;
}
.fa-search-custom {
  position: absolute;
  left: 375px;
  top: 123px;
  z-index: 99999;
}
</style>

<title>Geocoding API Demo</title>
</head>
  <body>
  <div style="height: 100vh;width: 100vw;" id="mapContainer" class="container-1"></div>
    <script>
        var platform = new H.service.Platform({
            apikey: `HERE-API-KEY`
        });
        var defaultLayers = platform.createDefaultLayers();

        //Step 2: initialize a map - this map is centered over Europe
        var map = new H.Map(document.getElementById('mapContainer'),
            defaultLayers.vector.normal.map, {
            center: { lat: 50, lng: 5 },
            zoom: 4,
            pixelRatio: window.devicePixelRatio || 1
        });
        // add a resize listener to make sure that the map occupies the whole container
        window.addEventListener('resize', () => map.getViewPort().resize());
        //Step 3: make the map interactive
        // MapEvents enables the event system
        // Behavior implements default interactions for pan/zoom (also on mobile touch environments)
        var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
    </script>
  </body>
  </html>

This code will render a web map like the image below.

Map

Add a Search Box to the Map

Once the HTML map is added, we will add code for the search box to the map. Copy the following HTML snippet inside the mapContainer div tag in the index.html after the script tag.

<div style="height: 100vh; width: 100vw;" id="mapContainer" class="container-1">
  <input placeholder="Search for a Place or an Address." type="text" name="search" id="search" value="Berlin, Germany" autocomplete="off" onkeyup="autosuggest(this)" autofocus/>
  <i class="fa fa-search fa-search-custom" aria-hidden="true"></i>
  <div class="dropdown">
    <ul id="list"></ul>
  </div>
</div>

Implement the Geocoding and Search API to Find the Geocoordinates

The Geocode endpoint is used to find geocoordinates of a location. Below is the endpoint.

https://autosuggest.search.hereapi.com/v1/autosuggest?at=52.5199813,13.3985138&limit=5&q=res&apiKey=YOUR_API_KEY_HERE

The response to the above request looks like the following:

{
  "items": [
    {
      "title": "Hackescher Hof",
      "id": "here:pds:place:276u33db-fb00197ffa5041b2b656ea3d23145dca",
      "resultType": "place",
      "address": {
        "label": "Hackescher Hof, Rosenthaler Straße 40, 10178 Berlin, Deutschland"
      },
      "position": { "lat": 52.52401, "lng": 13.40249 },
      "distance": 523,
      "categories": [ { "id": "100-1000-0000" }, ... ],
      "foodTypes": [ { "id": "300-000" }, ... ],
      "highlights": { "title": [ ], "address": { "label": [ ] } }
    },
    {
      "title": "restaurant",
      "id": "here:cm:ontology:restaurant",
      "resultType": "categoryQuery",
      "href": "http://ci.opensearch.dev.api.here.com/v1/discover?q=restaurant&_ontology=restaurant&at=52.51998%2C13.39851",
      "highlights": { "title": [{ "start": 0, "end": 3 }] }
    },
    {
      "title": "Cordobar",
      "id": "here:pds:place:276u33db-6b5445c1f1854148a8b351822a0ddc0c",
      "resultType": "place",
      "address": {
        "label": "Cordobar, Große Hamburger Straße 32, 10115 Berlin, Deutschland"
      },
      "position": { "lat": 52.52572, "lng": 13.39888 },
      "distance": 639,
      "categories": [ { "id": "100-1000-0000" }, ... ],
      "foodTypes": [ { "id": "300-000" }, ... ],
      "highlights": { "title": [ ], "address": { "label": [ ] } }
    },
    {
      "title": "McDonald's",
      "id": "here:pds:place:276u33db-dc6f6db9cef943c1b1ff3f74b30f03f9",
      "resultType": "place",
      "address": {
        "label": "McDonald's, Friedrichstraße 142, 10117 Berlin, Deutschland"
      },
      "position": { "lat": 52.52003, "lng": 13.38812 },
      "distance": 703,
      "categories": [{ "id": "100-1000-0009" }],
      "foodTypes": [{ "id": "800-067" }],
      "highlights": { "title": [ ], "address": { "label": [ ] } }
    },
    {
      "title": "Meliá Berlin",
      "id": "here:pds:place:276u33db-10e35e5ad0b0460e9fe49fc85a2bb8e7",
      "resultType": "place",
      "address": {
        "label": "Meliá Berlin, Friedrichstraße 103, 10117 Berlin, Deutschland"
      },
      "position": { "lat": 52.52138, "lng": 13.38833 },
      "distance": 706,
      "categories": [ { "id": "100-1000-0000" }, ... ],
      "foodTypes": [{ "id": "300-000" }, ... ],
      "highlights": { "title": [ ], "address": { "label": [ ] } }
    }
  ]
}

When the user starts typing in the search box, we will use the Autosuggest API to return address suggestions.

Add the below code in the index.html file anywhere in the <script> tag:

const autosuggest = (e) => {
  if(event.metaKey) {
    return
  } 
  let searchString = e.value
  if (searchString != "") {
    fetch(`https://autosuggest.search.hereapi.com/v1/autosuggest?apiKey=${apikey}&at=33.738045,73.084488&limit=5&resultType=city&q=${searchString}&lang=en-US`)
    .then(res => res.json())
    .then((json) => {
      if (json.length != 0) {
        document.getElementById("list").innerHTML = ``;
        let dropData = json.items.map((item) => {
          if ((item.position != undefined) & (item.position != ""))
            document.getElementById("list").innerHTML += `<li onClick="addMarkerToMap(${item.position.lat},${item.position.lng})">${item.title}</li>`;
          });
      }
    });
  }
};

Add a Marker to the Map

Once we find the desired location from the search box, lets add a marker to the map. To do that, copy the following code snippet to the script tag below the autosuggest function in the index.html file.

  // to get deafult location
  function getDeafultLocation(){
      var lat=52.5159;
      var lng=13.3777;
      var title = "Berlin, Germany";
      addMarkerToMap(lat, lng, title);
  }
  const addMarkerToMap = (lat, lng, title) => {
      map.removeObjects(map.getObjects())
      document.getElementById("search").value =  title;
      var selectedLocationMarker = new H.map.Marker({ lat, lng });
      map.addObject(selectedLocationMarker);
      document.getElementById("list").innerHTML = ``;
      map.setCenter({ lat, lng }, true); 
  };   

Final Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
    <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
    <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
    <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
    <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
    .dropdown {
      position: absolute;
      z-index: 99999;
      list-style-type: none;
      width: 360px;
      border: rgb(15, 22, 33);
      list-style: none;
      top: 135px;
    }
    input{
      z-index: 9999; font-size: 18px;
      font-family: 'Allerta', Helvetica, Arial, sans-serif;
      color: #495057;position: absolute; top: 100px; left: 20px; 
      width: 350px; height: 35px; padding: 5px; margin-left: 17px; 
      margin-top: 7px; border: none;
    }
    ul{
      list-style: none; 
      background-color: white; 
      padding: 0px;
      margin-left: 29px;
      width: 360px;
    }
    li{
      list-style-type: none;
      height: 12px;
      padding: 12px;
      box-shadow: rgb(158, 202, 237) 0px 0px 4px;
      display: list-item;
      text-align: -webkit-match-parent;
      font-family: 'Allerta', Helvetica, Arial, sans-serif;
      color: #495057;
      }
    li:hover {
      background-color: yellowgreen;
    }
    #list {
      cursor: pointer;
    }
    .fa-search-custom {
      position: absolute;
      left: 375px;
      top: 123px;
      z-index: 99999;
    }
    </style>
    <title>Geocoding Demo</title>
</head>
<body>
    <div style="height: 100vh; width: 100vw;" id="mapContainer" class="container-1">
      <input placeholder="Search for a Place or an Address." type="text" name="search" id="search"   value="Berlin, Germany" autocomplete="off" onkeyup="autosuggest(this)" autofocus />
      <i class="fa fa-search fa-search-custom" aria-hidden="true"></i>
      <div class="dropdown">
        <ul id="list"></ul>
      </div> 
    </div>
</body>
<script>
    function moveMapToBerlin(map) {
      map.setCenter({lat:52.5159, lng:13.3777});
      map.setZoom(10);
    }
    var platform = new H.service.Platform({
        apikey: `HERE-API-KEY` // replace with your api key
    });
    var defaultLayers = platform.createDefaultLayers();

    //Step 2: initialize a map - this map is centered over Europe
    var map = new H.Map(document.getElementById('mapContainer'),
        defaultLayers.vector.normal.map, {
        center: { lat: 50, lng: 5 },
        zoom: 4,
        pixelRatio: window.devicePixelRatio || 1
    });
    // add a resize listener to make sure that the map occupies the whole container
    window.addEventListener('resize', () => map.getViewPort().resize());

    //Step 3: make the map interactive
    // MapEvents enables the event system
    // Behavior implements default interactions for pan/zoom (also on mobile touch environments)
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));

    // Create the default UI components
    var ui = H.ui.UI.createDefault(map, defaultLayers);
    // Now use the map as required...
    window.onload = function () {
      moveMapToBerlin(map);
      getDeafultLocation();
    }  
    const autosuggest = (e) => {
      if(event.metaKey){
        return
      }

    let searchString = e.value
    if (searchString != "") {
      fetch(
        `https://autosuggest.search.hereapi.com/v1/autosuggest?apiKey=${window.apikey}&at=33.738045,73.084488&limit=5&resultType=city&q=${searchString}&lang=en-US`
      )
      .then((res) => res.json())
      .then((json) => {
        if (json.length != 0) {
          document.getElementById("list").innerHTML = ``;
          let dropData = json.items.map((item) => {
            if ((item.position != undefined) & (item.position != ""))
              document.getElementById("list").innerHTML += `<li onClick="addMarkerToMap(${item.position.lat},${item.position.lng},'${item.title}')">${item.title}</li>`;
          });
        }
      });
    }
    };
    // to get deafult location after loading the page
    function getDeafultLocation(){
      var lat=52.5159;
      var lng=13.3777;
      var title = "Berlin, Germany";
      addMarkerToMap(lat, lng, title);
    }
    // adding marker to map
    const addMarkerToMap = (lat, lng, title) => {
      map.removeObjects(map.getObjects())
      document.getElementById("search").value =  title;
      var selectedLocationMarker = new H.map.Marker({ lat, lng });
      map.addObject(selectedLocationMarker);
      document.getElementById("list").innerHTML = ``;
      map.setCenter({ lat, lng }, true); 
    };    
</script>

</html>
final-output

Conclusion

After going through this tutorial:

  • You should have learned how to use Geocoding and Search API in an application to search for an address.
  • You also develop the demo application using the HERE Maps API for JavaScript. Check out this documentation for more info.

Next Steps

Are you a Google Maps User? Then, the following tutorials will help you to transition to HERE Maps: