MapSnippets logo MapSnippets logo

Reverse Geocoding with OpenLayers

OpenLayers

Reverse geocode a clicked spot in OpenLayers by converting it with ol.proj.toLonLat, querying the MapTiler Geocoding API, and showing it in an ol.Overlay.

progress_activity Loading map...
var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '&copy; <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) })
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([2.3522, 48.8566]), zoom: 13 })
});
var popupEl = document.getElementById('popup');
var overlay = new ol.Overlay({ element: popupEl, positioning: 'bottom-center', offset: [0, -5] });
map.addOverlay(overlay);
map.on('click', function(evt) {
  var lonlat = ol.proj.toLonLat(evt.coordinate);
  popupEl.style.display = 'block';
  popupEl.textContent = 'Loading...';
  overlay.setPosition(evt.coordinate);
  fetch('https://api.maptiler.com/geocoding/' + lonlat[0].toFixed(6) + ',' + lonlat[1].toFixed(6) + '.json?key=YOUR_MAPTILER_KEY')
    .then(function(r) { return r.json(); })
    .then(function(data) {
      popupEl.textContent = data.features.length ? data.features[0].place_name : 'No address found';
    })
    .catch(function() { popupEl.textContent = 'Error fetching address'; });
});

How to get an address from a map click in OpenLayers

Reverse geocoding converts a coordinate into a human-readable address. This example uses a map click handler that sends the clicked position to the MapTiler Geocoding API.

ol.proj.toLonLat() converts the map’s internal EPSG:3857 coordinates back to [lng, lat] for the API request. Reverse geocoding uses the same endpoint, with coordinates in place of a search string.

The result is displayed in an ol.Overlay popup anchored to the click position.

Key APIs

API Description Docs
ol.proj.toLonLat() Convert map coords to [lng, lat] openlayers.org
MapTiler Geocoding API Reverse geocode coordinates to address docs.maptiler.com
ol.Overlay Anchor HTML element to map position openlayers.org

FAQ

What coordinate order does the API expect?

The MapTiler Geocoding API expects longitude,latitude in the URL, the same order that ol.proj.toLonLat() returns.

Can I get more detail about the result?

Yes. The API response includes multiple features ranked by specificity. features[0] is the most specific match. Each feature has place_type, text, and context properties.

Common mistakes

  • Using evt.coordinate directly in the API URL. It’s in EPSG:3857, not WGS84, so convert it with ol.proj.toLonLat() first.
  • Swapping longitude and latitude in the API URL, where the order is lng,lat
  • Not handling the case where no results are returned (empty features array)

Build maps using OpenLayers with AI

Generate code like this reverse geocoding with openlayers example using the OpenLayers skill in your IDE.