Saturday, 21 May 2022

Toggle multiple sidebars with separate map markers using Leaflet sidebar V2

Using Sidebar V2 (https://github.com/Turbo87/sidebar-v2) I've managed to create a sidebar and have a (leaflet.js) map marker that opens and close the sidebar using a 'toggleSidebar' function.

var sidebar = L.control.sidebar('sidebar').addTo(map);
var sidebarDiv = document.getElementById('sidebar');

toggleSidebar = function() {
  if (hasClass(sidebarDiv,'collapsed')) {
    sidebar.open();
  } else {
    sidebar.close();
  }
}

function hasClass(element, cls) {
  return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

var map = L.map("map");
map.setView([51.2, 7], 9);

// MARKER 1: ENGLAND
var marker = L.marker([52.5868, -2.1257], 
    {title: 'test', 
    riseOnHover: true, 
    autoPanOnFous: true,
    maxZoom: 28}
    ).addTo(map).on('click', function () {
    toggleSidebar();
});

Looking at the above code it seems that my 'marker' doesn't have any way of accessing the sidebar element ID, which is why I'm struggling to create a second marker that opens/closes a second sidebar.

Using Sidebar v1 I could do the following:

var marker1 = L.marker([52.6369, -1.1398], 
    {title: 'United Kingdom', 
    riseOnHover: true, 
    autoPanOnFous: true,
    maxZoom: 28}
    ).addTo(map).on('click', function () {
    sidebar1.toggle();
});

..so each marker could connect to each individual sidebar, but this can't be done with v2.

Any ideas?



from Toggle multiple sidebars with separate map markers using Leaflet sidebar V2

No comments:

Post a Comment