How to load React-map-gl with latitude and longitude set as users loaction by default?

1.2k views Asked by At

I want to render the map with default values of viewport set to user's location. Currently below code is for normal rendering and there is locate me button in the map when clicked it moves to that location. Any way to get it default clicked?

<ReactMapGL
    mapboxApiAccessToken={mapboxApiKey}
    mapStyle="mapbox://styles/mapbox/streets-v11"
    {...viewport}
    {...mapStyle}
     onViewportChange={this.handle_view}
    >
    <GeolocateControl
      positionOptions={{ enableHighAccuracy: true }}
      trackUserLocation={true}
    />
</ReactMapGL>
1

There are 1 answers

0
EVeras On

Following this answer: https://stackoverflow.com/a/59870917/14403123

 useEffect(() => {
    navigator.geolocation.getCurrentPosition(pos => {
      setViewport({
        ...viewport,
        latitude: pos.coords.latitude,
        longitude: pos.coords.longitude
      });
    });
  }, []);

A codesandbox showing the full code: https://codesandbox.io/s/intelligent-albattani-f596t?file=/src/App.js. However it won't show the map since I'm missing the token.