【问题标题】:get current location in first run在第一次运行时获取当前位置
【发布时间】:2018-10-22 07:10:30
【问题描述】:

我有一个使用位置服务的应用,但是当我请求当前位置并且在用户允许后,应用找不到位置。 为了让用户找到它的位置,必须关闭并重新打开应用程序,直到找到正确的位置。 这是我的代码:

componentWillMount() {
    this.getCurrentLocation();
}
getCurrentLocation = () => {
    const locationConfig = {
        timeout: 20000,
        maximumAge: 1000,
        enableHighAccuracy: false
    };
    navigator.geolocation.getCurrentPosition(
        this.iGetLocation,
        (error) => {
            console.log(error);
        },
        locationConfig
    );
};

【问题讨论】:

    标签: react-native geolocation


    【解决方案1】:

    我认为问题在于您的职位回调:this.iGetPosition。尝试使用回调函数,如下所示。 这对我有用(检查getCurrentPosition 函数):

     componentDidMount() {
            this.requestAccess();
     }
     requestAccess = async () => {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              'title': 'Location permission',
              'message': 'App needs access to your location ' +
                         'so we can show your location.'
            }
          )
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            navigator.geolocation.getCurrentPosition(
              (position) => {
                this.setState({
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude,
                  error: null,
                });
              },
              (error) => this.setState({ error: error.message }),
              { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
            );
    
          } else {
            console.log("Location permission denied")
          }
        } catch (err) {
          console.warn(err)
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      相关资源
      最近更新 更多