How do you call fitBounds() when using leaflet-react? How do you call fitBounds() when using leaflet-react? reactjs reactjs

How do you call fitBounds() when using leaflet-react?


Here is an example how to accomplish it via react-leaflet

handleClick() {    const map = this.mapRef.current.leafletElement;  //get native Map instance    const group = this.groupRef.current.leafletElement; //get native featureGroup instance    map.fitBounds(group.getBounds());}

where

<div>    <button onClick={this.handleClick}>Zoom</button>    <Map      center={this.props.center}      zoom={this.props.zoom}      ref={this.mapRef}    >      <TileLayer        attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"      />      <FeatureGroup ref={this.groupRef}>        {this.props.locations.map(location => (          <Marker            key={location.name}            position={{ lat: location.lat, lng: location.lng }}          >            <Popup>              <span>                <h4>{location.name}</h4>              </span>            </Popup>          </Marker>        ))}      </FeatureGroup>    </Map> </div>

which corresponds to

var leafletMap = new L.featureGroup([marker1, marker2, marker3]);map.fitBounds(leafletMap.getBounds());

Here is a demo


If you want this behavior on map load, you can use the onlayeradd event.

Example:

const fitToCustomLayer = () => {    if (mapRef.current && customAreaRef.current) { //we will get inside just once when loading        const map = mapRef.current.leafletElement        const layer = customAreaRef.current.leafletElement        map.fitBounds(layer.getBounds().pad(0.5))    }}return (<Map ref={mapRef} onlayeradd={fitToCustomLayer}>    <LayersControl position="topright">        <Overlay checked key="customArea" name="Área de interesse">            <GeoJSON ref={customAreaRef} data={collection} style={geoJSONStyle} />        </Overlay>        <BaseLayer name="Open Street Map">            <TileLayer attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'  url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>        </BaseLayer>                </LayersControl></Map>)

*Edit: If the ref layer is the last one, this doens't seems to work. Putting it before the base layers doesn't affect the rendering and it works.

If you need to use the onlayeradd for it's rightful purpose, make sure to add another flag to avoid getting inside the if and firing fitBounds again and lose map's current position.

Ps: I tried the onload method of react-leaflet, but it doesn't seems to work.