react-map-gl load map on the location of the user

747 Views Asked by At

Using react 18 and react-map-gl 7.0.11, im not able to load the map on the location of the user.

I am able to get this button on the screen using the GeoLocateControl component https://i.stack.imgur.com/fBy1y.png

<Map
  {...viewState}
  reuseMaps
  mapStyle="mapbox://styles/mapbox/streets-v9"
  mapboxAccessToken={process.env.REACT_APP_MAPBOX_KEY}
  onMove={(evt) => setViewState(evt.viewState)}
>
  <GeolocateControl
    positionOptions={{
      enableHighAccuracy: true,
    }}
    trackUserLocation={true}
    onGeolocate={(pos) => {
      setViewState({
        ...viewState,
        longitude: pos.coords.longitude,
        latitude: pos.coords.latitude,
      });
    }}
  />
</Map>

Is there a way, to trigger the button click to move the map and the blue dot to the current location of the user on mount of the component (map), without setting up event listeners? I tried the method of declaring a ref, and using useCallback to trigger the ref, but it did not work.

Any suggestions?

1

There are 1 best solutions below

0
On

as per https://blog.logrocket.com/using-mapbox-gl-js-react/: you can do something like:

function MyMap() {
  const [viewport, setViewport] = useState({});
  useEffect(() => {
    navigator.geolocation.getCurrentPosition((pos) => {
      setViewport({
        ...viewport,
        latitude: pos.coords.latitude,
        longitude: pos.coords.longitude,
        zoom: 3.5,
      });
    });
  }, []);
  return (
    <div>
      {viewport.latitude && viewport.longitude && (
        <div>
          <h1>Your Location:</h1>
          <Map
            mapboxAccessToken="MAPBOX_TOKEN"
            initialViewState={viewport}
            mapStyle="mapbox://styles/mapbox/streets-v11"
          >
            <Marker
              longitude={viewport.longitude}
              latitude={viewport.latitude}
            />
          </Map>
        </div>
      )}
    </div>
  );
}