Leaflet search control with data loaded from external GeoJSON file

by Alex Azuero

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="map"></div>

CSS

html, body, #map {
    height: 100%;
    width:100%;
    padding:0px;
    margin:0px;
    font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    color: #333;
}

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://dl.dropbox.com/s/ztt748q6kj8s3z9/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