How to set the map to a geolocation on map load with React-leaflet v3

Viewed 986

Hello I would like to load the map with the geolocation coordinates. Right now I have my map loaded on a defined center and when the event onClick happens, the view is set to the geolocate location. I just would like that this happens when I load the map the first time. My code below:

...
const Maps = () => {
// visitor geoLocalisation on the Map
  function LocationMarker() {
    const [position, setPosition] = useState(null);

    const map = useMapEvents({
      click() {
        map.locate();
      },
      locationfound(e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
      },
    });

    return position === null ? null : (
      <Marker
        position={position}
        icon={visitorIcon}
      >
        <Popup>You are here</Popup>
      </Marker>
    );
  }

  return (

    <MapContainer
      center={[48.856614, 2.3522219]}
      zoom={13}
      scrollWheelZoom
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />

      <LocationMarker />

   </MapContainer>

  );
}
2 Answers

Replace useMapEvents with a useEffect which will be triggered on component mount. Use a map.locate().on("locationfound") event to trigger geolocation.

function LocationMarker() {
    const [position, setPosition] = useState(null);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
      });
    }, []);

    return position === null ? null : (
      <Marker position={position} icon={visitorIcon}>
        <Popup>You are here</Popup>
      </Marker>
    );
  }

Demo

So finally I put map in the dependency and add a clenaup fonction to avoid Eslint and react Warnings above.

 function LocationMarker() {
    const [position, setPosition] = useState(null);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
      });
      return function cleanup() {
        map.stopLocate();
      };
    }, [map]);

    return position === null ? null : (
      <Marker position={position} icon={visitorIcon}>
        <Popup>You are here</Popup>
      </Marker>
    );
  }

Related