我如何获取用户的位置-在React Map GL中使用 [英] How can i get the location of the user - Using at React Map GL

查看:72
本文介绍了我如何获取用户的位置-在React Map GL中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React Map GL,我想输入用户的纬度和经度

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

像这样返回组件:

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

我尝试使用react-geolocated,但是它返回空坐标.

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 });
  }

}

地图组件:

<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}

推荐答案

我不知道如何使用Geolocate控件实现这一目标...但另一种选择是仅使用用户的设备位置&普通的javascript来获取当前位置...IE.像这样:

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
      });
    });
  }, []);

希望这对某人有帮助!

这篇关于我如何获取用户的位置-在React Map GL中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆