0

I have multiple overlays in my map that are all disabled by default:

var overlays = {
    'Overlay #1': overlay1,
    'Overlay #2': overlay2,
    'Overlay #3': overlay3
};

L.control.layers(baseMaps, overlays).addTo(mymap);

I'd like to make it so that when you click on a particular marker overlay2 appears. I'd like it to appear as checked in the Layer Control dialog and I'd like it to show up on the map as well. What isn't immediately obvious to me is (1) how to make it so that javascript is ran when a particular popup is opened or a particular marker clicked on and (2) how to turn overlays on as I've described.

Here's my marker code:

L.marker({lat: 30.266293, lon: -97.656965}, {icon: myIcon})
    .addTo(mymap)
    .bindPopup("<b>Hello world!</b>");

I guess I could make use of the popupopen event handler, looking at _source but is that the best way? That answer is almost eight years old.

As far as turning overlays on is concerned... Leaflet enable all overlays by default does $(".leaflet-control-layers-overlays label input").trigger('click') but that looks like that'll turn all the overlays on - not just one of them. I suppose I could do .eq(1) or some such but that seems super inelegant.

Any ideas?

neubert
  • 15,947
  • 24
  • 120
  • 212

1 Answers1

1

You can tap into an L.marker's on event, capture the click, and take some kind of action. Let's say we set up a group of associated markers and overlays:

// some markers
var littleton = L.marker([39.61, -105.02])
    .bindPopup("This is Littleton, CO.")
    .addTo(map),
  denver = L.marker([39.71, -105.12])
    .bindPopup("This is Denver, CO.")
    .addTo(map);

// some overlays:
const overlay1 = L.imageOverlay(imageUrl, [
  [39.61, -105.02],
  [39.71, -105.12]
]).addTo(map);

const overlay2 = L.imageOverlay(imageUrl, [
  [39.71, -105.12],
  [39.81, -105.22]
]).addTo(map);

We can add the overlays to the layer control:

var overlayMaps = {
  Overlay1: overlay1,
  Overlay2: overlay2,
};

L.control.layers(null, overlayMaps).addTo(map);

Then we can create an object that associates each marker with an overlay, and keeps track of whether or not its currently on the map:

const markerslayers = [
  {
    marker: littleton,
    overlay: overlay1,
    onmap: true
  },
  {
    marker: denver,
    overlay: overlay2,
    onmap: true
  }
];

For each marker, we can create an onclick event that toggles its associated overlay on or off:

markerslayers.forEach((mlayer) => {
  mlayer.marker.on("click", () => {
    if (mlayer.onmap) {
      mlayer.overlay.remove();
      mlayer.onmap = false;
    } else {
      mlayer.overlay.addTo(map);
      mlayer.onmap = true;
    }
  });
});

Working codesandbox

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78