Search code examples
leafletopenstreetmaplayermarker

Having Leaflet markers visible in more than one layer


I want some of my Leaflet markers visible in more than one layer on my Openstreetmap map.

By example: London is harbor and is also a capital city. So I want to see the London marker when I select only the layer 'harbors' or the layer 'capital cities'.

But the normal behaviour of Leaflet markers and layers seems to be that London only shows up when both layers 'harbors' and 'capital cities' are selected.

How to achieve to show up the London marker if just one of the two layers is selected?

Code:

var harbor  = L.layerGroup().addTo(map);
var capital = L.layerGroup().addTo(map);
      
var marker1 = L.marker([51.5, 0]);
marker1.addTo(harbor);
marker1.addTo(capital);

var overlays = { "Capital": capital, "Harbor": harbor}; 
L.control.layers(null, overlays).addTo(map);

Solution

  • The link @Tordanik gave, was helpfull. Adding this code does the job:

    map.on("overlayremove", function(o) {
            
      if (map.hasLayer(capital)) {
        map.removeLayer(capital);
        map.addLayer(capital);
      }
            
      if (map.hasLayer(harbor)) {
        map.removeLayer(harbor);
        map.addLayer(harbor);
      }
            
    });
    

    Steps taken after an ovelayremove-click:

    1. Test each layers if it is active
    2. Remove this layer
    3. Place this layer with his markers back Result: all the markers in this layer are visible again.