12

I want to get bounds of the current map so that I can search those bounds with the Overpass API.

For leaflet I know the method is just map.getBounds(), but I don't know how to implement that in react-leaflet.

class SimpleExample extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }

  componentDidMount() {
    console.log(this.refs.map.getBounds())
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <Map center={position} zoom={this.state.zoom} ref='map'>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
      </Map>
    );
  }
}

This is what I've tried. Error says that this.refs.map.getBounds isn't a function.

Jake Hm
  • 327
  • 1
  • 2
  • 13

2 Answers2

12

Try this.refs.map.leafletElement.getBounds.

According to the documentation:

You can directly access the Leaflet element created by a component using this.leafletElement in this component. This leaflet element is usually created in componentWillMount(), except for the Map component where it can only be created after the container is rendered.

which is a round about way of saying they store the leaflet object as leafletElement property on their component objects.

Chris Owens
  • 5,076
  • 12
  • 61
  • 131
Brandon
  • 38,310
  • 8
  • 82
  • 87
  • i kind of don't get the part `except for the Map component where it can only be created after the container is rendered.` am i able to get new bounds for each render? thank you – Martin Brisiak Nov 23 '17 at 17:58
  • 2
    Access it in `componentDidMount` and `componentDidUpdate` – Brandon Nov 23 '17 at 19:02
  • 1
    You can also take a look to https://stackoverflow.com/questions/51399480/react-leaflet-how-to-get-map-bounds-and-center-it if this answer doesn't fix the problem (for me, the `ref='map'` part was missing) – Stéphane Apr 23 '19 at 20:24
  • 1
    refs is deprecated – dhiraj Mar 29 '21 at 08:13
0

I stumbled upon this earlier, the way I solved it is by using the useMap hook from react-leaflet like this:

import { useMap } from "react-leaflet";

function ShowBounds() {
const mMap = useMap();
let newBounds = mMap.getBounds();
console.log(newBounds);
}

Worked for me. Hope this helps.

Anass
  • 301
  • 1
  • 3
  • 13