Search code examples
javascriptreactjsleafletreact-leaflet

How to use getBounds() to get pick up map ends with react-leaflet?


How to get the 4 coordinates that represent the 4 ends visible on the map using react-leaflet.

I would like to use the contains() function to return true or false for a coordinate that is passed, if it is true it means that it is within the limits established in getBounds(), if it is false it is outside.

Just wiht leaflet in pure JavaScript I know how to use this function. But I'm developing a React Web Application, and I'm using react-leaflet library and need use this function.

Thank you in advance for any help.

Here's my code I put into codesandbox

import React from "react";
import { Map, TileLayer } from "react-leaflet";

import "./styles.css";

const App = () => {
  const center = [51.505, -0.09];

  const [map, setMap] = React.useState(null);

  React.useEffect(() => {
    if (map) {
      const contains = map.getBounds().contains(center);
      console.log("contains:: ", contains);
    }
  }, [center, map]);

  return (
    <Map
      ref={setMap}
      style={{ width: "100%", height: "100vh" }}
      center={center}
      zoom={13}
    >
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
    </Map>
  );
};

export default App;


Solution

  • You need to get a reference to the map. Then you can access the ref's .leafletElement property, which is the map instance:

    const App = ({ center }) => {
      const mapRef = useRef();
    
      React.useEffect(() => {
        if (mapRef) {
          const contains = mapRef.leafletElement.getBounds().contains(center);
        }
      }, [center]);
    
      return (
        <Map 
          ref={mapRef}
          {...otherProps}
        >
          <TileLayer {...props} />
        </Map>
      );
    };
    

    Working codesandbox


    Modern answer for react-leaflet v4

    You need a reference to the map, so that you can call things like L.map.getBounds(). react-leaflet no longer uses the .leafletElement property since react-leaflet v3. Here's a v4 answer:

    const App = ({ center }) => {
      const [map, setMap] = useState(null)
    
      React.useEffect(() => {
        if (map) {
          const contains = map.getBounds().contains(center);
        }
      }, [center]);
    
      return (
        <Map 
          ref={setMap}
          {...otherProps}
        >
          <TileLayer {...props} />
        </Map>
      );
    };
    

    The docs have some examples of how to grab the underlying L.map instance as a ref and use it, here: https://react-leaflet.js.org/docs/example-external-state/.