Search code examples
reactjsleafletreact-leaflet

How to overlay a div on a React-Leaflet map?


I want to create a card on top of my React-Leaflet map that shows some details of the map. But my first issue is that, I can not overly my div(container of card) on top of map. here is my code:


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];
    return (
      <LeafletMap center={position} zoom={this.state.zoom}
        id='mapDiv'
        >
        <div
          style={{
            width: 500,
            height: 500,
              top: 0,
                left: 0,
                  backgroundColor: 'red',
                    zIndex: 10
          }}  
        />
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <Marker position={position}>
          <Popup>
            A pretty CSS3 popup. <br/> Easily customizable.
          </Popup>
        </Marker>
      </LeafletMap>
    );
  }
}


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

Solution

  • Make your div a sibling of the map container, not a child:

    <div 
      className="container"
      style={{
        position: 'relative'
        width: 500,
        height: 500
      }}
    >
      <div
        style={{
          position: 'absolute'
          width: 500,
          height: 500,
          top: 0,
          left: 0,
          zIndex: 10000
        }}  
      />
      <LeafletMap {...props}>
        {mapChildren}
      </LeafletMap>
    </div>
    

    You can see an example of this with vanilla leaflet here: Make Select Option Display on top of Leaflet Map