[GIS] Why in Leaflet does baselayerchange event not fire until the second time the base layer is changed

javascriptleaflet

I am attempting to fire an event when the base layer changes in a Leaflet Map. It seems that the event is only firing on the "second" time the layer changes? Here is a fiddle to display an alert on baselayerchange, showing this condition.

https://jsfiddle.net/frugardc/x5p2nLrs/112/

Here is the code

// center of the map
var center = [-33.8650, 151.2094];
// Set up the OSM layer
var l1 = L.tileLayer(
  'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 18
});
var l2 = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
   attribution: '&copy; <a 
href="http://osm.org/copyright">OpenStreetMap</a> contributors'
});
// Create the map
var map = L.map('map',{layers: [l1,l2]}).setView(center, 3);

baseLayers = {
  'Map 1': l1,
  'Map 2': l2
};
L.control.layers(baseLayers,{}).addTo(map);

map.on('baselayerchange', function(e) {
  alert('Changed to ' + e.name);
});
// add a marker in the given location
L.marker(center).addTo(map);

Best Answer

I examined behaviour of internal _onLayerChange event handler which fires 'baselayerchange' event. Event is fired only when base layer is added.

So the story goes like this. If map is created with

var map = L.map('map',{layers: [l1,l2]});

both layers are added to the map at time of creation. When you initialy select the other layer, previous one is removed and select one shown. Since it does not need to be added, 'baselayerchange' event is not fired. If you then select the other layer, it has to be added (since it was removed) and 'baselayerchange' event is fired.

You can verify this if you initialy select the layer that is already shown (this will remove the other layer) and then the other layer. In this case 'baselayerchange' event is fired.

One possible solution is to create map only with initial layer:

var map = L.map('map',{layers: [l1]});

In this case event is fired even at the first display of map and at every subsequent change of layer.