TransWikia.com

Changing info div based on baselayer selection

Geographic Information Systems Asked by Luca Moiana on January 25, 2021

I would like to change the map logo in a info div based on the baselayer selection.

From what I understood, I have to use events but I do not know how.

Here is my code:

    <!-- Add LOGO -->

var info = L.control({position: 'bottomleft'});

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};

map.on('baselayerchange', function(eventLayer) {
if (eventLayer.name === 'MapboxDark') {
    info.update = function (props) {
            this._div.innerHTML = '<img src="./images/logo_notte.jpg" alt="Notte" height="100" width="87">';
            };
}
if (eventLayer.name === 'MapboxOutdoor') {
    info.update = function (props) {
            this._div.innerHTML = '<img src="./images/logo_giorno.jpg" alt="Notte" height="100" width="87">';
            };
            info.addTo(map);
}

});
info.addTo(map);

One Answer

You just need to adjust the innerHTML of your info._div HTML Element on "baselayerchange" event. No need to change an update() method.

var info = L.control({
  position: 'bottomleft'
});

info.onAdd = function(map) {
  this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
  //this.update(); // your update() method may not be defined yet, if no baselayerchange occured?
  return this._div;
};

info.addTo(map);

info._div.innerHTML = "OSM"; // fill with default base layer name.

map.on('baselayerchange', function(eventLayer) {
  switch (eventLayer.name) {
    case "OSM":
      info._div.innerHTML = "OSM";
      break;
    case "B&W":
      info._div.innerHTML = "Black & White";
      break;
  }
});

Demo: https://jsfiddle.net/3v7hd2vx/48/

Correct answer by ghybs on January 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP