首页 > 解决方案 > How can i get the location of the user - Using at React Map GL

问题描述

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}

标签: reactjsgeolocationreact-map-gl

解决方案


我不知道如何使用 Geolocate 控件来实现这一点......但另一种方法是只使用用户的设备位置和纯 javascript 来获取当前位置...... IE 像这样的东西:

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

希望这对某人有帮助!


推荐阅读