Javascript Tutorial: How to search addresses with Geocoding API

Geocoding is an essential part of serving location-based services such as maps and local search. But let's clarify which type of Geocoding API you need for your project, Forward Geocoding API or Reverse Geocoding API, or maybe Autocomplete API?

  • Forward Geocoding API is used to get a verified address and its coordinates by provided a free-form address string.
  • Reverse Geocoding API allows converting latitude/longitude coordinates into an address. For example, the common use-case for Reverse Geocoding API will be getting the address for a building a user clicked on.
  • Autocomplete API tries to guess an address by a given part of the address. For example, when you enter "rue la mon" the autocomplete will return "Rue La Montagne, Port-au-Prince, Haiti", "Rue la Montagne, La Coudre, France", and "Rue la Montjoie, Saint-Sever-de-Rustan, France".

This Javascript Tutorial will focus on the Forward Geocoding API and learn how to search addresses by user-entered address string.

Get address location and show it on a map

Let's implement a simple address search with Javascript. We will use Vanilla Javascript methods for HTTP Get call and the Leaflet map library for a map.

"A user enters an address into a form field. Then, on a button click, the input field's value is validated and displayed in individual form inputs for each address component and on a map."

We can split the task into the following subtasks:

  • Search address entered by a user on a button click;
  • Display the address components in the address form;
  • Display the found locations on a map.

Geocode address on button click

Let's create an input field and a button. Then, we will call the "geocodeAddress()" method on a button click:

<div class="address-line">
  <input id="address" type="text" placeholder="Enter address to search"><button onclick="geocodeAddress()">Geocode</button>
</div>

In the "geocodeAddress()" method, we get the address value and call Geoapify Geocoding API to get the corresponding location for the address. It also makes sense to add a check if the address is not too small:

function geocodeAddress() {
  const address = document.getElementById("address").value;
  if (!address || address.length < 3) {
    console.log("The address string is too short. Enter at least three symbols");
    return;
  }

  const geocodingUrl = `https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent(address)}&apiKey=${myAPIKey}`;

  // call Geocoding API - https://www.geoapify.com/geocoding-api/
  fetch(geocodingUrl).then(result => result.json())
    .then(featureCollection => {
      console.log(featureCollection);
    });
}

Learn how to get a Geoapify API key and start using the API on the Getting Started page >>

Get the formatted address and the address components

The Geocoding API returns GeoJSON.FeatureCollection object. The object may have one or more features. Each feature contains an address option found.

Let's add the result address form:

<div class="address-line">
  <input id="address" type="text" placeholder="Enter address to search"><button onclick="geocodeAddress()">Geocode</button>
</div>
<div class="results">
  <label for="name">Name:</label>          
  <input id="name" type="text" readonly />
  <label for="house-number">House number:</label>          
  <input id="house-number" type="text" readonly />
  <label for="street">Street:</label>          
  <input id="street" type="text" readonly />
  <label for="postcode">Postcode:</label>          
  <input id="postcode" type="text" readonly />
  <label for="city">City:</label>          
  <input id="city" type="text" readonly />
  <label for="state">State:</label>          
  <input id="state" type="text" readonly />
  <label for="country">Country:</label>          
  <input id="country" type="text" readonly />
</div>
<div class="status">
  <span id="status">Enter address and press "Geocode" button</span>
</div>

And display the found address there. The full address we will show in the "status" string:

function geocodeAddress() {
  const address = document.getElementById("address").value;
  if (!address || address.length < 3) {
    document.getElementById("status").textContent = "The address string is too short. Enter at least three symbols";
    return;
  }

  const geocodingUrl = `https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent(address)}&apiKey=${myAPIKey}`;

  // call Geocoding API - https://www.geoapify.com/geocoding-api
  fetch(geocodingUrl).then(result => result.json())
    .then(featureCollection => {
      if (featureCollection.features.length === 0) {
        document.getElementById("status").textContent = "The address is not found";
        return;
      }

      const foundAddress = featureCollection.features[0];
      document.getElementById("name").value = foundAddress.properties.name || '';
      document.getElementById("house-number").value = foundAddress.properties.housenumber || '';
      document.getElementById("street").value = foundAddress.properties.street || '';
      document.getElementById("postcode").value = foundAddress.properties.postcode || '';
      document.getElementById("city").value = foundAddress.properties.city || '';
      document.getElementById("state").value = foundAddress.properties.state || '';
      document.getElementById("country").value = foundAddress.properties.country || '';

      document.getElementById("status").textContent = `Found address: ${foundAddress.properties.formatted}`;
    });
}

The API returns multiple addresses when there are more than one locations with the same address or when the exact address is not found. The most confident option is always the first. Therefore, the API response contains the "confidence" value that helps decide if the address is correct.

Show the address on a map

We will use the Leaflet map library for this tutorial:

  • You can install the Leaflet by running "npm i leaflet" or add it from a CDN as a link.
  • Learn more about Leaflet integration on the official Leaflet Download page.
  • Check our JSFiddle code to learn how to integrate a Leaflet map into a webpage.

Let's show the found location with a marker on a map. Don't forget to remove the previously added marker when adding a new one. The "map.panTo()" method will pan the map to the found location:

// Marker to save the position of found address
let marker;
function geocodeAddress() {

  ...

  // remove the previously added marker
  if (marker) {
    marker.remove();
  }

  fetch(geocodingUrl).then(result => result.json())
    .then(featureCollection => {

      ...

      // add a new marker and adjust the map view
      marker = L.marker(new L.LatLng(foundAddress.properties.lat, foundAddress.properties.lon)).addTo(map);
      map.panTo(new L.LatLng(foundAddress.properties.lat, foundAddress.properties.lon));
    });
}

Full Javascript Tutorial code on JSFiddle

Here is the whole Javascript code used for this tutorial:

What's next