Javascript Tutorial: How to get address by coordinates with Reverse Geocoding API

Geoapify Reverse Geocoding API JSFiddle
Geoapify Reverse Geocoding API JSFiddle

The Reverse Geocoding API helps to get an address by its latitude/longitude coordinates. For example, it's helpful to know a building address a user clicked on or get user location information by GPS coordinates.

For example, for when you pass latitude = 39.46927181 and longitude = -0.382334280, the Reverse Geocoding API returns the building address "Estética Ana Salmerón, Carril Bici de la Ronda Interior, 43, 46004 Valencia, Spain" and separate address components, like city = Valencia, postcode = 46004, street = "Carril Bici de la Ronda Interior", house number = 43, etc.

This tutorial demonstrates how to use the Reverse Geocoding API in Javascript. Whenever the user clicks on a map, we find his location address and show it.

Get address by latitude/longitude and show it on a map

Let's see how the Reverse Geocoding API works in practice. Let's get the address on the map!

To make the solution more descriptive, we split the task into smaller ones:

  • Call Reverse Geocoding API on a map click event
  • Show the returned address on a map
  • Show the address components in an address form

You will need a Geoapify API key to run the code on your side. Learn how to get an API key on the Getting Started page >>.

Query an address on a map click

We use a Leaflet map for the Javascript Reverse Geocoding Tutorial. The Leaflet Download page describes in detail how you can add a Leaflet map to your project. Moreover, the JSFiddle, we've prepared for this tutorial, contains a Javascript code that shows how to add and initialize a Leaflet map.

Here is a code sample showing how to add a click event to the map and call a Reverse Gecodcoding API:

function onMapClick(e) {
  const reverseGeocodingUrl = `https://api.geoapify.com/v1/geocode/reverse?lat=${e.latlng.lat}&lon=${e.latlng.lng}&apiKey=${myAPIKey}`;
  
  // call Reverse Geocoding API - https://www.geoapify.com/reverse-geocoding-api/
  fetch(reverseGeocodingUrl).then(result => result.json())
    .then(featureCollection => {
      console.log(featureCollection);
    });
}

map.on('click', onMapClick);

The Geoapify Reverse Gecoding API returns a GeoJSON.FeatureCollection as a reponse.

Show the location on a map

We show the returned location with a marker on a map. We use the same marker constant to store the marker object, so don't forget to remove the previously added one before adding new:

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

  if (marker) {
    marker.remove();
  }

  // call Reverse Geocoding API - https://www.geoapify.com/reverse-geocoding-api/
  fetch(reverseGeocodingUrl).then(result => result.json())
    .then(featureCollection => {
      ...
      marker = L.marker(new L.LatLng(foundAddress.properties.lat, foundAddress.properties.lon)).addTo(map);
    });
}

Show address in an address form

Let's create separate form elements for each address component:

<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">Click on the map to query an address by coordinates</span>
</div>

Let's display name, house number, street, city, postcode, state, and country in the address form:

function onMapClick(e) {

  ...

  // call Reverse Geocoding API - https://www.geoapify.com/reverse-geocoding-api/
  fetch(reverseGeocodingUrl).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}`;
      ...
    });
}

Reverse Geocoding Javascript Tutorial code on JSFiddle

We've created a JSFiddle that grants you to try the code above and play with it:

What's next