Geoapify + Leaflet: Address Search Plugin Demo

Add an address autocomplete to a Leaflet map

More examples: Custom styling, Localize results, Search nearby, Beautiful markers

This plugin uses Geoapify Location Platform to search addresses and suggests address completion. You can read about the result addresses format on the documentation page.

You'll need an API key to use Geoapify. Register now and get your key on myprojects.geoapify.com. Free accounts permit up to 3000 requests a day.

Here is a sample of how to add the Address Search Plugin to your Leaflet map:


var map = L.map('my-map').setView([48.1500327, 11.5753989], 6);
var marker = null;

var myAPIKey = "YOUR_API_KEY"; // Get an API Key on https://myprojects.geoapify.com
var mapURL = L.Browser.retina
  ? `https://maps.geoapify.com/v1/tile/{mapStyle}/{z}/{x}/{y}.png?apiKey={apiKey}`
  : `https://maps.geoapify.com/v1/tile/{mapStyle}/{z}/{x}/{y}@2x.png?apiKey={apiKey}`;

// Add map tiles layer. Set 20 as the maximal zoom and provide map data attribution.
L.tileLayer(mapURL, {
  attribution: 'Powered by Geoapify | © OpenMapTiles © OpenStreetMap contributors',
  apiKey: myAPIKey,
  mapStyle: "osm-bright-smooth", // More map styles on https://apidocs.geoapify.com/docs/maps/map-tiles/
  maxZoom: 20
}).addTo(map);

// Add Geoapify Address Search control
const addressSearchControl = L.control.addressSearch(myAPIKey, {
  position: 'topleft',
  resultCallback: (address) => {
    if (marker) {
      marker.remove();
    }
    
    if (!address) {
      return;
    }

    marker = L.marker([address.lat, address.lon]).addTo(map);
    if (address.bbox && address.bbox.lat1 !== address.bbox.lat2 && address.bbox.lon1 !== address.bbox.lon2) {
      map.fitBounds([[address.bbox.lat1, address.bbox.lon1], [address.bbox.lat2, address.bbox.lon2]], { padding: [100, 100] })
    } else {
      map.setView([address.lat, address.lon], 15);
    }
  },
  suggestionsCallback: (suggestions) => {
    console.log(suggestions);
  }
});
map.addControl(addressSearchControl);
L.control.zoom({ position: 'bottomright' }).addTo(map);