2

Id like to have multiple popups on the map that are open when the map loads, I've got the example from this answer working for one popup:

Popup always open in the marker

But when I have multiple popups, only one is open on load and opening one closes the other - in the leaflet docs (http://leafletjs.com/reference-1.0.0.html#popup) it suggests using addLayer to avoid this but I can't figure out how to recreate that in react-leaflet:

const React = window.React;
const { Map, TileLayer, Marker, Popup, MapLayer, LayerGroup } = window.ReactLeaflet;

class SimpleExample extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    const position2 = [this.state.lat - 0.01, this.state.lng];
    return (
      <Map center={position} zoom={this.state.zoom}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <ExtendedMarker position={position}>
          <Popup>
            <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
          </Popup>
        </ExtendedMarker>

        <ExtendedMarker position={position2}>
         <Popup position={position2}>
            <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
          </Popup>
        </ExtendedMarker>


      </Map>
    );
  }
}

// Create your own class, extending from the Marker class.
class ExtendedMarker extends Marker {
    // "Hijack" the component lifecycle.
  componentDidMount() {
    // Call the Marker class componentDidMount (to make sure everything behaves as normal)
    super.componentDidMount();

    // Access the marker element and open the popup.
    this.leafletElement.openPopup();
  }
}

window.ReactDOM.render(<SimpleExample />, document.getElementById('container'));

https://jsfiddle.net/37uo2cp5/

Community
  • 1
  • 1
SteveH
  • 46
  • 5

1 Answers1

2

Anyone stumbling on this question, in a later version of leaflet (eg: 1.0.0+) there is an option autoClose in the Popup's options which you can set to false to display multiple popups.

<Map center={position} zoom={this.state.zoom}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
    />
    <ExtendedMarker position={position}>
      <Popup autoClose={false}>
        <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
      </Popup>
    </ExtendedMarker>

    <ExtendedMarker position={position2}>
     <Popup position={position2} autoClose={false}>
        <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
      </Popup>
    </ExtendedMarker>


  </Map>
Vandesh
  • 6,368
  • 1
  • 26
  • 38