Tuesday, 7 February 2017

javascript - Activating Search Plugin with JS Leaflet


I am attempting to add the following plugin to search a GeoJSON file I have open in Leaflet Javascript: http://labs.easyblog.it/maps/leaflet-search/examples/geojson-layer.html


I have brought in the search js and css files and called them, I just do not understand the syntax to incorporate it into the existing script.


Here is the script it needs to be able to search (the field is Sheet_Numb):


$.getJSON("Syriashape.json",function(data){
// add GeoJSON layer and popups to the map once the file is loaded

L.geoJson(data, {
style: function (feature) {
return {};
},
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.Sheet_Numb + "
" + " " + feature.properties.LOC_Catalo);
}
}).addTo(map);
});


I know I have to add the following somewhere:


map.addLayer(featuresLayer);
var searchControl = new L.Control.Search({layer: featuresLayer, 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) {

featuresLayer.eachLayer(function(layer) { //restore feature color
featuresLayer.resetStyle(layer);
});
});

map.addControl( searchControl ); //inizialize search control

Answer



You need to assign your L.geoJson layer to a named var outside the getJSON function in order to access it via controls. First, create it without any data, along with whatever options you want to apply to the features:



//create empty geoJson layer to be populated later
//styles, popups and other layer options can be specified here
var syriaLayer = L.geoJson(false, {
style: function (feature) {
return {};
},
onEachFeature: function (feature, layer) {
layer.bindPopup("Sheet Number: " + feature.properties.Sheet_Numb + "
"
+ "Catalog Record: " + "" + feature.properties.LOC_Catalo + "");
}

});

Then you can use addData to populate it with the data from your file:


$.getJSON("Syriashape.json", function (data) {
// add GeoJSON data to layer and add to the map once the file is loaded
syriaLayer.addData(data).addTo(map);
});

Then, because you have defined syriaLayer, you can refer to it (and Sheet_Numb) when you create your search control:


var searchControl = new L.Control.Search({layer: syriaLayer, propertyName: 'Sheet_Numb', circleLocation:false});


Here is a working fiddle that searches by state using the data from the example you linked to:


http://fiddle.jshell.net/nathansnider/ma33L8hx/


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...