0

I have a set of markers that have binded popups, but I can't figure out how to show all the popups when the marker group is toggled in the layers control.

For example, I have my markers like so:

var testMarker = L.marker([32.9076,33.35449]).bindPopup('Marker 1');
var testMarkerTwo = L.marker([33.58259,34.64539]).bindPopup('Marker 2');

Then, I put it in a freature group and append the openPopup method:

var markerGroup = L.featureGroup([testMarker,testMarkerTwo]).openPopup().addTo(map);

This doesn't work.

My final goal is to add that featureGroup to my layers control where I can toggle the group off/on. Before I get to that part, I need to first understand why the openPopup method is not working.

Edit: The answer below appears to only work with the plain Leaflet API, not the Mapbox API.

redshift
  • 4,815
  • 13
  • 75
  • 138

1 Answers1

1

There are a couple problems here. The first is that by default, Leaflet closes the previously opened popup each time another is opened. The second is that, while your markers have popups bound to them, markerGroup does not, and even if it did, markerGroup.openPopup would only cause a single popup to open.

To get around the first problem, you can use the hack from this answer. If you place the following code at the beginning of your script (before you define your map) it will override the default behavior and allow you to open multiple popups at once:

L.Map = L.Map.extend({
    openPopup: function(popup) {
        this._popup = popup;
        return this.addLayer(popup).fire('popupopen', {
            popup: this._popup
        });
    }
});

Then, once you are able to open multiple popups, you can open all popups in markerGroup using the eachLayer method:

var markerGroup = L.featureGroup([testMarker,testMarkerTwo]).addTo(map);
markerGroup.eachLayer(function(layer) {
  layer.openPopup();
});

Here is an example fiddle:

http://fiddle.jshell.net/nathansnider/02gsb1Lt/

Community
  • 1
  • 1
nathansnider
  • 2,773
  • 1
  • 14
  • 17
  • Thank you for that. For some reason when I run your example on my local test, I only get one popup, not two like in your example. I'm using the mapbox js api..not sure if that matters? – redshift Apr 13 '16 at 17:54
  • 1
    Hmm. Yes, using mapbox.js will prevent the multiple popup workaround from working. I believe that this is because redefining `L.Map` with `L.Map.extend` will not modify the behavior of `L.mapbox.map` (which was previously extended from `L.Map`). There may a be another workaround for use with Mapbox, but for the moment I'm not sure exactly what it would look like. – nathansnider Apr 13 '16 at 18:27