简体   繁体   中英

How to use bounds with dynamic markers in react-leaflet

I have the following functional react component which correctly displays two static markers within a 'bounds' box which fits both markers inside.

I would like to be able to pass in an array of latitude and longitude values for the map to display but I can't work out how to do it.

This is the working, static example:

import React from 'react'
import { MapContainer, TileLayer, Marker } from 'react-leaflet'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

const MapLeaflet = () => {

// STATIC MARKER POSITIONS
const position = [42.2974279, -85.628292];
const position2 = [-8.852507, -45.351563];

// BOUNDS CODE
const bounds = L.latLngBounds([position, position2]);

return (
    <MapContainer
        className=" map"
        center={position}
        bounds={bounds}
    >
        <Marker key={key} position={position}>
            <Heart/>
        </Marker>
        <Marker key={key} position={position2}>
            <Heart/>
        </Marker>

        <TileLayer
            attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
    </MapContainer>
        
)
}

If I pass is {coords} I can then dynamically display the markers:

const MapLeaflet = ({coors}) => {
...
    { coords && coords.map(coord => (
           <Marker key={key} latitude={coord[0]} longitude={coord[1]}>
                <SomeMarker/>
           </Marker>
    ))}
...
}

But obviously, the map is not yet taking these 'coords' into consideration for the bounds. The console.log output of the passed in coords array is as follows:

0: (2) [51.52167056034225, -0.12894469488176763]
1: (2) [46.58635156377568, 2.1796793230151184]
2: (2) [40.819721, 14.341111]

Somehow I need to replace the following line with a reference to the passed in coords in a format the code accepts, but I can't work out how to do it.

const bounds = L.latLngBounds([position, position2]);

to something like

const bounds = L.latLngBounds({coords});

Any help would be very much appreciated.

Kind regards, Matt

I think I understood what you want to achieve.

maxBounds is immutable in react-leaflet v.3 therefore you need to create a custom component that will change the map bounds upon coords change. It will take coords as prop and it will change the map bounds when coords change or when the comp lands.

function Bounds({ coords }) {
  const map = useMap();
  useEffect(() => {
    if (!map) return;

    map.fitBounds(coords);
  }, [map, coords]);
  return null;
}

In your app comp I included a case where bounds change (coords variable) and the map bounds change accordingly. Hopefully this is what you are looking for.

function App() {
  const [coords, setCoords] = useState([
    [51.52167056034225, -0.12894469488176763],
    [46.58635156377568, 2.1796793230151184],
    [40.819721, 14.341111]
  ]);

  return (
    <>
      <MapLeaflet coords={coords} />
      <button
        onClick={() =>
          setCoords([
            [52.52167056034225, -0.12894469488176763],
            [47.58635156377568, 2.1796793230151184],
            [41.819721, 14.341111]
          ])
        }
      >
        Change coords
      </button>
    </>
  );
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM