Reverse geocoding uses the user’s location to search for places

This example demonstrates the process of discovering locations by inputting coordinates (known as reverse geocoding) obtained from the user’s current position. Reverse geocoding transforms coordinates into place names.

By default, the example displays the user’s location, which is determined based on their IP address. However, you also have the option to manually enter specific coordinates in the designated text fields or utilize the map interface (click on the map) to search for places at those particular coordinates.

NPM module setup


npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';

config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';

const map = new Map({
  container: 'map', // container's id or the HTML element to render the map
  style: MapStyle.STREETS.LIGHT,
  geolocate: maptilersdk.GeolocationType.POINT
});

map.on('click', async (e) => {
  const {lng, lat} = e.lngLat;
  document.getElementById('lat').value = lat;
  document.getElementById('lng').value = lng;
  reverseGeocoding(lng, lat);
});

map.on('load', function() {
  const {lng, lat} = map.getCenter();
  document.getElementById('lat').value = lat;
  document.getElementById('lng').value = lng;
  reverseGeocoding(lng, lat);
});

document.getElementById('btn-search-reverse').addEventListener('click', function() {
  const lng = parseFloat(document.getElementById('lng').value);
  const lat = parseFloat(document.getElementById('lat').value);
  reverseGeocoding(lng, lat);
});

let marker;

async function reverseGeocoding(lng, lat){
  if (!lng || !lat || lng === "" || lat === "") {
    document.getElementById('results').innerHTML = "";
  } else{
    const result = await maptilersdk.geocoding.reverse([lng, lat]);
    document.getElementById('results').innerHTML = JSON.stringify(
      result,
      null,
      2
    );
    if (marker) {
      marker.setLngLat([lng, lat]);
    } else {
      marker = new maptilersdk.Marker()
      .setLngLat([lng, lat])
      .addTo(map);
    }
    map.flyTo({
      center: [
        lng,
        lat
      ],
      padding: {right: window.innerWidth/2},
      essential: true // this animation is considered essential with respect to prefers-reduced-motion
    });
  }
}
Geocoding: Show place search results

Geocoding API

Tutorials

Search for places using the MapTiler Geocoding API.

How to search places by coordinates (reverse geocoding)

Reverse geocoding

Tutorials

Search places by coordinates using reverse geocoding.

Geocoding search results closer to specific point

Geocoding search results by proximity to a specific point

Examples

Rank geocoding search results higher based on proximity.

Geocoding search results to specified country(ies)

Geocoding search results to specified country(ies)

Examples

Limit geocoding control search results to specific countries.

Was this helpful?