Say I have the following code:
var streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
var yearLayers = {};
yearLayers['1877'] = L.tileLayer('https://terrafrost.sfo2.digitaloceanspaces.com/maps/austin/v2/1877/{z}/{x}/{y}.png');
var map = L.map('map', {
center: [30.267222, -97.743056],
zoom: 13,
layers: [streets]
});
layerControl = L.control.layers().addTo(map);
layerControl.addBaseLayer(streets, 'Streets');
layerControl.addOverlay(yearLayers['1877'], '1877');
layerControl.removeLayer(yearLayers['1877']);
/*
var years = ['1877'];
for (var i = 0; i < years; i++) {
year = years[i];
layerControl.removeLayer(yearLayers[year]);
}
*/
That code runs without issue but, if I comment out the layerControl.removeLayer(yearLayers['1877']); and uncomment out the for loop I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'off')
at i.removeLayer (Control.Layers.js:142:9)
at whatever:x:y
https://jsfiddle.net/q7rkzjLp/2/ shows what I mean. Well, more specifically, that link shows the error.
https://jsfiddle.net/q7rkzjLp/1/ shows it code without the for loop running without issue.
So why am I getting this error and what can I do to fix it?