Reverse Geocoding with MapLibre GL JS
MapLibre GL JSTurn a map click into an address in MapLibre GL JS by sending its lng,lat to the MapTiler Geocoding API and showing the result in a maplibregl.Popup.
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 to get an address from a map click in MapLibre GL JS
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. The coordinates use lng,lat order, the 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, notlat,lng - Not handling empty results, which some ocean or remote areas return
- Creating multiple markers without removing the previous one
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
- Address Search with MapLibre GL JS
- See how to do this in Leaflet, MapTiler SDK, or OpenLayers