leafletreact-leaflet

React Leaflet: How to get access to the Map object after first render?


I have a parent component with two children:

  1. a Leaflet map
  2. a list of locations visible on the map (calculated using the map's getBounds())

I'm having a problem initializing that list of locations. Some things I tried:

So how do I trigger a callback in the parent with the bounds of the map after it is finished loading?


Solution

  • When working with react leaflet I think its easier to create components that you can place within your MapContainer that can handle specific tasks e.g. Bounds

    Here is how I get the bounds of the map:

    const Bounds: React.FC<{ onMove: (bounds: MapBounds) => void }> = ({
      onMove,
    }) => {
      const map = useMapEvent("moveend", (event) => {
        onMove(convertBounds(event.sourceTarget.getBounds()));
      });
    
      const convertBounds = (bounds: any) => {
        const southWest = bounds.getSouthWest();
        const northEast = bounds.getNorthEast();
    
        return {
          min: {
            lat: southWest.lat,
            lng: southWest.lng,
          },
          max: {
            lat: northEast.lat,
            lng: northEast.lng,
          },
        };
      };
    
      // set inital bounds, important that onMove is not changed because that wil cause loop
      useEffect(() => {
        onMove(convertBounds(map.getBounds()));
      }, [onMove, map]);
    
      return <></>;
    };
    

    Then You can just add <Bounds onMove={onBoundsChange} /> as a child to MapContainer.