Skip to content Skip to sidebar Skip to footer

How Do You Call FitBounds() When Using Leaflet-react?

I cannot figure out how to call fitBounds() on the Leaflet map. If I was just using vanilla leaflet, this solution would work perfectly: Zoom to fit all markers in Mapbox or Leafle

Solution 1:

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='&amp;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


Solution 2:

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='&amp;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.


Post a Comment for "How Do You Call FitBounds() When Using Leaflet-react?"