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?

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

1 Answers1

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]]

          ]);
      }}
    &gt;
      &lt;TileLayer
        attribution='&amp;copy; &lt;a href=&quot;https://www.openstreetmap.org/copyright&quot;&gt;OpenStreetMap&lt;/a&gt; contributors'
        url=&quot;https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&quot;
      /&gt;
      {data &amp;&amp; (
        &lt;GeoJSON data={data} 
        style={style} 
        onEachFeature={onEachFeature} /&gt;
      )}
    &lt;/MapContainer&gt;

Aliénor
  • 31
  • 6