How to make Leaflet Search actually search

Viewed 9760

Implementing the Leaflet Search example just produces a search box. Nothing happens when you open it and start typing. The leaflet search code isn't being executed. It just shows the red Location not found. The graph shows area's of interest and I need to do something with the area's that match search criteria, to identify them to the user.

var searchLayer = L.layerGroup().addTo(map);
//... adding data in searchLayer ...
map.addControl( new L.Control.Search({layer: searchLayer}) );
//searchLayer is a L.LayerGroup contains searched markers

There is code in the control to search to the data. It takes into account a geoJson data structure.

What am I missing in order to activate the search code?

1 Answers

Although not explicitly explained in Leaflet Control Search README, the plugin will use the data in marker.options.title or in feature.properties.title by default.

You can specify a different key than title using the propertyName option when instantiating the Search Control:

var map = L.map('map').setView([41.8990, 12.4977], 14);

var poiLayers = L.geoJSON(restaurant, {
  onEachFeature: function(feature, layer) {
    layer.bindPopup(feature.properties.amenity + '<br><b>' + feature.properties.name + '</b>');
  }
});

L.control.search({
    layer: poiLayers,
    initial: false,
    propertyName: 'name' // Specify which property is searched into.
  })
  .addTo(map);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<link rel="stylesheet" href="https://unpkg.com/leaflet-search@2.3.7/dist/leaflet-search.src.css" />
<script src="https://unpkg.com/leaflet-search@2.3.7/dist/leaflet-search.src.js"></script>

<script src="http://labs.easyblog.it/maps/leaflet-search/examples/data/restaurant.geojson.js"></script>

<div id="map" style="height: 200px"></div>

Related