MapSnippets logoMapSnippets logo

Reverse Geocoding with OpenLayers

OpenLayers

Click anywhere on an OpenLayers map to get the address at that location using the MapTiler Reverse Geocoding API.

progress_activityLoading 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 it works

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. The API URL format for reverse geocoding is the same endpoint but with coordinates instead 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 returned by ol.proj.toLonLat().

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. Use ol.proj.toLonLat() first
  • Swapping longitude and latitude in the API URL: the order is lng,lat
  • Not handling the case where no results are returned (empty features array)
auto_awesome

Build maps using OpenLayers with AI

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