How to add a search box on a leaflet map

24,803

Solution 1

There are many solutions available to adding a search control to a leaflet map. Some are listed on the Leaflet Plugin page under Search and Popups. The search control needs some data to conduct the search, so you should have access to some data on your map. You can host the data on your map or connect to some remote data source(s).

Search Local Level Locations:

If your search criteria is to retrieve data you hosted on the map, then I recommend the Leaflet Search plugin maintained by Stefano Cudini See a working example on this link.

Read more at: https://gis.stackexchange.com/questions/130623/adding-a-search-box-to-a-leaflet-js-example

Search Global Level Locations:

If you want the search criteria to search for random places around the world (that is the database isn't in your app), then use a custom solution provided by a company like ESRI Leaflet project. See working example this codepen page: 'leaflet map with place search'.

enter image description here

<!DOCTYPE html>
<html>
<head>
    <title>LeafletJS with Search Box</title>

   <!-- CSS and JS files for Search Box -->
    <script src="https://cdn-geoweb.s3.amazonaws.com/esri-leaflet/0.0.1-beta.5/esri-leaflet.js"></script>

    <script src="https://cdn-geoweb.s3.amazonaws.com/esri-leaflet-geocoder/0.0.1-beta.5/esri-leaflet-geocoder.js"></script>

    <link rel="stylesheet" type="text/css" href="https://cdn-geoweb.s3.amazonaws.com/esri-leaflet-geocoder/0.0.1-beta.5/esri-leaflet-geocoder.css">

</head>
<body>

        <div id="map"></div>

    <script type="text/javascript">

        // This setup the leafmap object by linking the map() method to the map id (in <div> html element)
        var map = L.map('map', {
              center: [51.517327, -0.120005],
              zoom: 1.5,
              // minZoom: 1.5,
             //  maxZoom: 1.5
            });

        // Start adding controls as follow... L.controlName().addTo(map);

        // Control 1: This add the OpenStreetMap background tile
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
              attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);


        // Control 2: This add a scale to the map
            L.control.scale().addTo(map);

        // Control 3: This add a Search bar
            var searchControl = new L.esri.Controls.Geosearch().addTo(map);

            var results = new L.LayerGroup().addTo(map);

              searchControl.on('results', function(data){
                results.clearLayers();
                for (var i = data.results.length - 1; i >= 0; i--) {
                  results.addLayer(L.marker(data.results[i].latlng));
                }
              });

    </script>

</body>
</html>

Solution 2

This solution works with last versions of leaflet and geosearch. First load scripts from unpkg.com (the order is important here).

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"/>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/geosearch.css"/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bundle.min.js"></script>
<script>
  jQuery(document).ready(function($) {
    var map = L.map('map', {
      center: [36.979120, -121.899390],
      zoom: 5
    }); //Creates a leaflet map centered at center [latitude, longitude] coordinates.

    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      subdomains: ['a', 'b', 'c']
    }).addTo(map); //Creates the attribution box at the top bottom right of map.

    const provider = new window.GeoSearch.OpenStreetMapProvider();
    const search = new GeoSearch.GeoSearchControl({
      provider: provider,
      style: 'bar',
      updateMap: true,
      autoClose: true,
    }); // Include the search box with usefull params. Autoclose and updateMap in my case. Provider is a compulsory parameter.

    L.marker([51.0, -0.09]).addTo(map).bindPopup('A pretty CSS3 popup.<br> Easily customizable.'); //Creates a marker at [latitude, longitude] coordinates.
  });
</script>

<div id="map"></div> // Creates the wrapper cotaining the map
Share:
24,803

Related videos on Youtube

Anchor
Author by

Anchor

Updated on September 09, 2021

Comments

  • Anchor
    Anchor over 2 years

    I want to use a leaflet map to be a page's background. And this page has a search function, but this search box is not used to search this map. So my question is how to add a search box on a leaflet map?

    Do you have any other solution to use a map to be the background? like this page: http://directory.spatineo.com/

    • Anchor
      Anchor almost 8 years
      I want to use a leaflet map to be a page's background.And this page has a search function,but this search box is not use to search this map. So my question is how to add a search box on a leaflet map? Do you have any other solution to use a map to be the background.
    • snkashis
      snkashis almost 8 years
      Have you looked into custom controls with L.Control?(leafletjs.com/reference.html#control)
    • Anchor
      Anchor almost 8 years
      Yes,L.Control' controls are all about to control the map,but not has the search box control..
    • muzaffar
      muzaffar almost 8 years
      @Anchor, add any html element on your page and set its position as absolute and set top and left/right position, this way you can add search box on map
    • snkashis
      snkashis almost 8 years
      Yes, L.Control is the boilerplate for leaflet controls,they are extremely flexible, you add whatever elements you need, but it's up to you to add the search functionality...just add an input field and add listeners as needed.
  • Yun Jae Jung
    Yun Jae Jung over 3 years
    Does including the Geocoding by Esri suffice in meeting license conditions? Or will there need to be more lengthy accreditation if this is going to be for an web app? -I noticed that Esri also sites data providers, or is that only for map tiling?
  • atline
    atline over 3 years
    You may want to add explain.
  • hamlet237
    hamlet237 over 3 years
    Explained atline. Thank you.
  • Sean William
    Sean William about 2 years
    It seems you missed map.addControl(search);