1

I'm new to using React-leaflet. I want to getBounds of my GeoJSON but I don't figure out how.

I want to use it instead of [48.832,2.623], [48.900, 2.800] in my code.

<MapContainer
          zoom={10}
          scrollWheelZoom={false}
          maxZoom={14}
          center={[48.832,2.623]}
          whenReady={e => {
            mapRef = e.target;
            e.target.flyToBounds([
                [48.832,2.623],
                [48.900, 2.800]
              ]);
          }}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          {data && (
            <GeoJSON data={data} 
            style={style} 
            onEachFeature={onEachFeature} />
          )}
</MapContainer>

In the V2 and V3 I see on other questions that we can use mapRef.leafletElement.getBounds() But no longer in tha V4 because when I use it, have got an error of: Uncaught TypeError: Cannot read properties of undefined (reading 'getBounds')

I try with the answer of this question, but it doesn't work either

Can someone help me do it in the new version of react-leaflet please?

3
  • Are you getting the bounding box of the geojson object and passing them to flyToBounds? - gis.stackexchange.com/questions/166863/…
    – Cary H
    Oct 17, 2022 at 18:45
  • Yes this is what I want to do
    – Aliénor
    Oct 18, 2022 at 6:20
  • Thanks the bbox works like a charm, have a great day @CaryH
    – Aliénor
    Oct 18, 2022 at 13:33

1 Answer 1

2

Thanks to CaryH in the comments, I can use BBox that return an array of [left, bottom, right, top] of the box that contain the entite in the GeoJSON. The docs of geojson-bbox is in here

So the code is :

const bbox = require('geojson-bbox');

const extent = bbox(data); 

<MapContainer
          zoom={10}
          scrollWheelZoom={false}
          maxZoom={14}
          center={[48.832,2.623]}
          whenReady={e => {
            mapRef = e.target;
            e.target.flyToBounds([
              [extent[1],extent[0]],
              [extent[3], extent[2]]
                
              ]);
          }}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          {data && (
            <GeoJSON data={data} 
            style={style} 
            onEachFeature={onEachFeature} />
          )}
        </MapContainer>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.