How can i get the location of the user - Using at React Map GL

荒凉一梦 提交于 2021-02-07 18:28:18

问题


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}

回答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!



来源:https://stackoverflow.com/questions/57617959/how-can-i-get-the-location-of-the-user-using-at-react-map-gl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!