MapSnippets logoMapSnippets logo

Reverse Geocoding with MapLibre GL JS

MapLibre GL JS

Click anywhere on a MapLibre GL JS map to get the address at that location using the MapTiler reverse geocoding API.

progress_activityLoading map...
const map = new maplibregl.Map({
  container: 'map',
  style: 'https://api.maptiler.com/maps/streets-v4/style.json?key=YOUR_MAPTILER_KEY',
  center: [14.42, 50.08],
  zoom: 12
});
map.addControl(new maplibregl.NavigationControl());
let marker;
map.on('click', async (e) => {
  const { lng, lat } = e.lngLat;
  const res = await fetch(`https://api.maptiler.com/geocoding/${lng},${lat}.json?key=YOUR_MAPTILER_KEY`);
  const data = await res.json();
  if (marker) marker.remove();
  const name = data.features.length ? data.features[0].place_name : 'Unknown location';
  marker = new maplibregl.Marker({ color: '#F44336' })
    .setLngLat(e.lngLat)
    .setPopup(new maplibregl.Popup({ offset: 25 }).setHTML(`<b>${name}</b><br>${lng.toFixed(5)}, ${lat.toFixed(5)}`))
    .addTo(map);
  marker.togglePopup();
});

How it works

Reverse geocoding converts coordinates into a human-readable address. On each map click, the snippet sends the lng,lat pair to the MapTiler geocoding endpoint and displays the closest address in a popup.

The API returns results ordered by proximity. The first feature is the most specific match: typically a street address or POI. The response includes multiple features at different levels of detail (address, place, region, country).

The marker is replaced on each click by removing the previous one first.

Key APIs

API Description Docs
MapTiler Reverse Geocoding Coordinates to address docs.maptiler.com
map.on('click') Listen for map click events maplibre.org docs
e.lngLat Coordinates of the click event maplibre.org docs

FAQ

What is the URL format for reverse geocoding?

https://api.maptiler.com/geocoding/{lng},{lat}.json?key=YOUR_MAPTILER_KEY: note the lng,lat order, same as GeoJSON.

Can I get results in a specific language?

Yes. Add &language=en (or cs, de, etc.) to the URL to get localized place names.

Common mistakes

  • Swapping lat and lng in the API URL: the format is lng,lat, not lat,lng
  • Not handling empty results: some ocean or remote areas return no features
  • Creating multiple markers without removing the previous one
auto_awesome

Build maps using MapLibre GL JS with AI

Generate code like this reverse geocoding with maplibre gl js example using the MapLibre GL JS skill in your IDE.

Related Examples