MapSnippets logo MapSnippets logo

Reverse Geocoding with Leaflet

Leaflet

Reverse geocode a clicked point on a Leaflet map with map.on('click') and the MapTiler Geocoding API, then show the address in a popup.

progress_activity Loading map...
const map = L.map('map').setView([48.8566, 2.3522], 13);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
let marker;
map.on('click', async (e) => {
  const { lat, lng } = e.latlng;
  const res = await fetch(`https://api.maptiler.com/geocoding/${lng},${lat}.json?key=YOUR_MAPTILER_KEY`);
  const data = await res.json();
  const label = data.features.length ? data.features[0].place_name : 'Unknown location';
  if (marker) marker.remove();
  marker = L.marker([lat, lng]).addTo(map).bindPopup(label).openPopup();
});

How to get an address from a map click in Leaflet

Reverse geocoding converts coordinates into a human-readable address. The map listens for click events via map.on('click'), which provides the clicked location as e.latlng. The coordinates are sent to the MapTiler Geocoding API in lng,lat order (GeoJSON convention).

The API returns the nearest address as a GeoJSON feature collection. The first feature’s place_name is displayed in a popup at the clicked location. Each new click replaces the previous marker.

Key APIs

API Description Docs
MapTiler Geocoding Reverse geocoding endpoint docs.maptiler.com/cloud/api/geocoding
map.on('click') Map click event leafletjs.com/reference.html#map-click
e.latlng Clicked coordinates leafletjs.com/reference.html#mouseevent

FAQ

What does the reverse geocoding URL look like?

The URL is https://api.maptiler.com/geocoding/{lng},{lat}.json?key=YOUR_MAPTILER_KEY, with longitude first.

How precise is the result?

The API returns the most specific feature at that location, typically a street address. You can filter by type with &types=address,poi.

Common mistakes

  • Passing coordinates as lat,lng in the URL when the API expects lng,lat order
  • Not handling the case where no features are returned (e.g., clicking in the ocean)
  • Forgetting that e.latlng is a Leaflet LatLng object, not an array

Build maps using Leaflet with AI

Generate code like this reverse geocoding with leaflet example using the Leaflet skill in your IDE.