Search code examples
javascriptjqueryleafletreact-leaflet-search

How to implement autocomplet place search box with Leaflet API


I would like to ask you how to implement just search box function from leaflet-search plugin and just for two countries. I want to make input field for location inserting with function of autocomplete.

I tried to implement search box with map first, but I can see just map and no search box.

Can you advice me where to start? I am new in it and I do not know way to go.

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '© OpenStreetMap'
}).addTo(map);


var searchLayer = L.geoJson().addTo(map);
//... adding data in searchLayer ...
L.map('map', { searchControl: {layer: searchLayer} });  


Solution

  • Check out the L.Control.Geocoder plugin for Leaflet. This plugin allows you to search for locations using a number of different services like Open Street Maps.

    To limit the search results to a some countries, you have to configure the geocoding service that you use. I have created a quick example using OSM/Nominatim that limits the search results to the UK and US:

    var map = L.map('map').setView([51.505, -0.09], 13);
    
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    }).addTo(map);
    
    let geoCoderOptions = {
      collapsed: false,
      geocoder: L.Control.Geocoder.nominatim({
            geocodingQueryParams: {
              // List the country codes here
              countrycodes: 'gb,us'
            }
        })
    }
    
    L.Control.geocoder(geoCoderOptions).addTo(map);
    

    See working example on codepen. If you search for a location (input in the top-right corner), you should only get results that are in the UK or the US. Hope this helps!