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 instanceconstgroup = this.groupRef.current.leafletElement; //get native featureGroup instance
    map.fitBounds(group.getBounds());
}

where

<div><buttononClick={this.handleClick}>Zoom</button><Mapcenter={this.props.center}zoom={this.props.zoom}ref={this.mapRef}
    ><TileLayerattribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      /><FeatureGroupref={this.groupRef}>
        {this.props.locations.map(location => (
          <Markerkey={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:

constfitToCustomLayer = () => {
    if (mapRef.current && customAreaRef.current) { //we will get inside just once when loadingconst map = mapRef.current.leafletElementconst layer = customAreaRef.current.leafletElement
        map.fitBounds(layer.getBounds().pad(0.5))
    }
}

return (
<Mapref={mapRef}onlayeradd={fitToCustomLayer}><LayersControlposition="topright"><Overlaycheckedkey="customArea"name="Área de interesse"><GeoJSONref={customAreaRef}data={collection}style={geoJSONStyle} /></Overlay><BaseLayername="Open Street Map"><TileLayerattribution='&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?"