I am encountering challenges while using the Leaflet.Control.Search plugin by Stefano Cudini in conjunction with Leaflet's built-in function L.control.layers.
When all layers are active, there are no issues with locating a specific area.
However, when one of the layers is deactivated, Leaflet-Search fails to pinpoint a location. An error message appears in the search box as follows:
Uncaught TypeError: Cannot read property 'layerPointToLatLng' of null
at e.getBounds (leaflet.js:5)
at e._searchInLayer (leaflet-search.js:555)
at leaflet-search.js:594
at eachLayer (leaflet.js:5)
at e._searchInLayer (leaflet-search.js:593)
at leaflet-search.js:605
at eachLayer (leaflet.js:5)
at e._recordsFromLayer (leaflet-search.js:604)
at e._fillRecordsCache (leaflet-search.js:744)
at leaflet-search.js:706
If you re-enable the hidden layer, the search functionality returns to its normal operation.
I have created a JS Bin illustrating the issue, although it may not display the exact error details due to only showing "script error". Go ahead and try searching for a site - available names include 1000, 1100, 1110, and 1111. It should work initially. Then disable one of the layer groups from the layer control and attempt to search again - an error will be triggered. Re-enabling the layer group will restore normal functionality.
I would greatly appreciate any suggestions on what might be going wrong or potential workarounds. Thank you in advance!
In short, here is the relevant code:
The sites are defined in two arrays:
var sites1 = [
{"loc":[51.582521, -0.118155],"Site":"1000"},
{"loc":[51.587454, -0.106052],"Site":"1100"}
];
These arrays are iterated through and added to a layer group:
var layerSites1 = L.layerGroup();
for(var i in sites1) {
var title = sites1[i].Site,
loc = sites1[i].loc,
marker = new L.circle(new L.latLng(loc),
{radius: 100,title: title,color: 'red'})
.bindPopup('Site: '+ title);
layerSites1.addLayer(marker);
}
The two layer groups are designated as overlays:
var overlays = {
"Sites1": layerSites1,
"Sites2": layerSites2
};
L.control.layers(baseLayers,overlays).addTo(mymap);
They are then combined into a collective layer group used for searching by Leaflet Search:
var layerAll = L.layerGroup([layerSites1,layerSites2]);
The Leaflet Search configuration is outlined below:
var controlSearch = new L.Control.Search({
position:'topright',
layer: layerAll,
initial: false,
hideMarkerOnCollapse: true,
zoom: 17
});
mymap.addControl(controlSearch);