Intro to Leaflet  |  Searching Layers via Leaflet Search

One of the benefits of Leaflet is the vast amount of free plugins avaible. In this map we are using the Leaflet Search plugin. It provides either a global address search or a feature search. Here we are searching the County layer on the ‘NAME’ field. However, since we are searching data that must be loaded into the browser, we have to wait until the data is loaded before we can call the search function. The omnivore plugin solves this for us since it has a built in event that is fired once the data is loaded. If you are using jQuery to load the data, you can use the .done() method.

« Adding and Styling Points Leaflet Choropleth »

Full Map Code

      
var map = L.map("map");

map.setView([40.3,-96.6], 5);

L.hash(map);

L.control.scale().addTo(map);

var layerControl = new L.control.layers(null, null).addTo(map);

/*Easily add basemaps or baselayers with L.tileLayer wms layers can also be added with L.tileLayer.wms */

var OpenStreetMap_HOT = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
}).addTo(map);

layerControl.addBaseLayer(OpenStreetMap_HOT, "Streets");

var url = "/gis-tutorials/tutorial-data/counties.topojson";

var counties = L.geoJson().addTo(map);

/*can put html inside here, this is one way you could add a legend*/
layerControl.addOverlay(counties, "Counties");

var cData = omnivore.topojson(url, null, counties);

// Search

cData.on("ready", function() {

	var searchControl = new L.Control.Search({
		layer: counties,
		propertyName: 'NAME',
	}).addTo(map);

});