Leaflet search control with data loaded from external GeoJSON file
HTML
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<script src="http://labs.easyblog.it/maps/leaflet-search/src/leaflet-search.js"></script>
<link rel="stylesheet" href="http://labs.easyblog.it/maps/leaflet-search/src/leaflet-search.css">
<div id="was"><span>Leaflet Search Control Example</span></div>
<div id="map"></div>
CSS
html, body, #map {
height: 100%;
width:100%;
padding:0px;
margin:0px;
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
}
#was
{
width:300px;
height:35px;
line-height: 35px;
text-align:center;
border-radius:5px;
background: rgba(255,255,255,0.7);
position:absolute;
top:10px;
left:calc(50% - 150px);
margin:auto;
z-index: 2000;
display: inline-block;
border:1px solid #7585F0;
}
span {
display: inline-block;
vertical-align: middle;
font-weight:bold;
}
JavaScript
var map = new L.Map('map', {
zoom: 4,
center: new L.latLng([37.8, -96])
});
map.addLayer(new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')); //base layer
//create empty geoJson layer to be populated later
//styles, popups and other layer options can be specified here
var statesLayer = L.geoJson(false, {
style: function (feature) {
return {};
},
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.name + "</br>" + " " + feature.properties.density);
}
});
// Load GeoJSON data, add it to the layer, and add that the map once the file is loaded
$.getJSON("https://gist.githubusercontent.com/anonymous/aaeb2cd525bee8424bfe/raw/123434feb330777d6ca213a0f548e48502ebdc9a/states.json", function (data) {
statesLayer.addData(data).addTo(map);
});
var searchControl = new L.Control.Search({
layer: statesLayer,
propertyName: 'name',
circleLocation: false
});
searchControl.on('search_locationfound', function (e) {
e.layer.setStyle({
fillColor: '#3f0',
color: '#0f0'
});
if (e.layer._popup) e.layer.openPopup();
}).on('search_collapsed', function (e) {
statesLayer.eachLayer(function (layer) { //restore feature color
statesLayer.resetStyle(layer);
});
});
map.addControl(searchControl); //inizialize search control