Tuesday, 12 November 2019

javascript - L.Control.Search: Using looping for searching data on Leaflet


Is there a way to find data from different layers and different propertyNames? I have several GeoJSON data files, with different properties. At this moment I can only search one GeoJSON.


For looping and calling the data I am using this code:


maplink_var = [source1.geojson,source2.geojson,etc]; 

var = new L.GeoJSON(, {

style: function(feature) {
...
},
onEachFeature: function(feature, marker) {
...
}
});

and below is the code to find data:


var searchControl = new L.Control.Search({

layer: source1,source2,source3,
propertyName: ['propNameSource1','propNameSource2','propNameSource3'],
marker: false,
moveToLocation: function(latlng, title, map) {
var zoom = map.getBoundsZoom(latlng.layer.getBounds());
map.setView(latlng, zoom); // access the zoom
}
});

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) {
featuresLayer.resetStyle(layer);
});
});

map.addControl( searchControl );


I get an error if I give array on property name, stack on loading, and none of the data appears.


enter image description here



Answer



As explained in the documentation layer is a L.LayerGroup. Thus you can pass multiple layers like this (source):


var searchControl = new L.Control.Search({
layer: L.layerGroup([source1, source2, source3]),
...
})

As for the propertyName: The property name must be the same for all GeoJSON files. Try this when you create the L.GeoJSON (not tested):



onEachFeature: function(feature, layer) {
const p = feature.properties
p.title = p.propNameSource1 || p.propNameSource2 || p.propNameSource3 //create new property 'title'
}

title is the default for propertyName so you won't even have to set it when you create L.Control.Search.


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...