Geoapify + Leaflet: Address Search Plugin Demo

Show locations with beautiful markers

More examples: Add the address autocomplete plugin, Custom style, Localize results, Search nearby

The Geoapify Address Autocomplete plugin notifies when new addresses are suggested and when an address has been selected. So, you can visualize the suggestions and results on a map.

Make your maps more attractive by using the Marker Icon API by generating a set of customizable markers for your maps:


var marker = null;
var suggestionMarkers = [];
const suggestionsMarkerIcon = L.icon({
  iconUrl: `https://api.geoapify.com/v1/icon/?type=awesome&shadowColor=%23fafafa&color=%23fff351&size=small&scaleFactor=2&apiKey=${myAPIKey}` /* get an API Key on https://myprojects.geoapify.com */,
  iconSize: [25, 37], // size of the icon
  iconAnchor: [12.5, 34], // the point on the icon which will correspond to the marker's location, substruct the shadow
  popupAnchor: [0, -36] // the point from which the popup should open relative to the iconAnchor
});

const resultMarkerIcon = L.icon({
  iconUrl: `https://api.geoapify.com/v1/icon/?type=awesome&shadowColor=%23fafafa&color=%2336d867&scaleFactor=2&apiKey=${myAPIKey}` /* get an API Key on https://myprojects.geoapify.com */,
  iconSize: [31, 46],
  iconAnchor: [15.5, 42],
  popupAnchor: [0, -45] 
});      

const addressSearchControl = L.control.addressSearch(myAPIKey /* get an API Key on https://myprojects.geoapify.com */, {
  position: 'topleft',
  resultCallback: (address) => {
    if (marker) {
      marker.remove();
    }

    if (suggestionMarkers) {
      suggestionMarkers.forEach(marker => marker.remove());
      suggestionMarkers = [];
    }

    if (!address) {
      return;
    }

    marker = L.marker([address.lat, address.lon], {icon: resultMarkerIcon}).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) => {
    if (marker) {
      marker.remove();
    }

    if (suggestionMarkers) {
      suggestionMarkers.forEach(marker => marker.remove());
      suggestionMarkers = [];
    }

    if (!suggestions || !suggestions.length) {
      return;
    }

    const bbox = L.latLngBounds();
    suggestions.forEach(suggestion => {
      bbox.extend([suggestion.lat, suggestion.lon]);
      suggestionMarkers.push(L.marker([suggestion.lat, suggestion.lon], {icon: suggestionsMarkerIcon}).bindPopup(suggestion.formatted).addTo(map));
    });

    if (bbox.isValid) {
      map.fitBounds(bbox, { padding: [100, 100] })
    } else {
      map.setView([suggestions[0].lat, suggestions[0].lon], 15);
    }
  }
});
map.addControl(addressSearchControl);
L.control.zoom({ position: 'bottomright' }).addTo(map);