4

I'm using React Map GL, and I want to put the latitude and longitude of the user

Returning the component like this:

export default geolocated({
  positionOptions: {
    enableHighAccuracy: false
  },
  userDecisionTimeout: 5000
})(Layout);

I'm tried to use react-geolocated but it's returning null coords.

I want to get these informations when the component mounts, that's the code:

 componentDidMount() {

    console.log(this.props);
    if (navigator.geolocation) {

     const viewport = {
         ...this.state.viewport,
         latitude: this.props.coords.latitude,
        longitude: this.props.coords.longitude
     };

       this.setState({ viewport });
  }

}

The map component:

<MapGL
            {...viewport}
            //onClick={this.handleMapClick}
            mapStyle="mapbox://styles/mapbox/streets-v9"
            mapboxApiAccessToken={TOKEN}
            perspectiveEnabled
            onViewportChange={viewport => this.setState({ viewport })}
          >
            <div className="geo" style={geolocateStyle}>
              {" "}
              <GeolocateControl
                positionOptions={{ enableHighAccuracy: true }}
                trackUserLocation={true}
              />
            </div>

            <div className="nav" style={navStyle}>
              <NavigationControl
                onViewportChange={viewport => this.setState({ viewport })}
              />
            </div>
          </MapGL>

I'm getting the props like this:

{coords: null, isGeolocationAvailable: true, isGeolocationEnabled: true, positionError: null}
Laura Beatris
  • 1,782
  • 7
  • 29
  • 49

1 Answers1

1

I don't know how to achieve this using the Geolocate control... but an alternative would be to just use the user's device location & plain javascript to fetch the current location... I.E. Something like this:

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

Hope this helps someone!

Ally Haire
  • 2,398
  • 1
  • 14
  • 19
  • This is a fair solution, but opens the question: how do you initialize the center of the map? If you use an arbitrary default, then the user location might not be within viewport. If you wait to render the map, how are you blocking it? thanks! – DeBraid Jun 24 '20 at 15:32
  • I haven't used this for awhile, but I seem to remember the map having a hook that would control rendering - you could also create your own to stop rendering before getting the location back – Ally Haire Jul 15 '20 at 04:16