在 Reactnative 中自动获取当前位置 [英] To get Current Location Automatically in Reactnative

查看:40
本文介绍了在 Reactnative 中自动获取当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法可以通过单击按钮来获取当前位置,它将获取当前位置.我想在不点击那个按钮的情况下获取位置.

I have this method to fetch current location by clicking button it will fetch current location . I want to fetch location without clicking that button .

getLocationHandler = () =>{
   navigator.geolocation.getCurrentPosition(pos =>{

    const coordsEvent ={ 
      nativeEvent :{
        coordinate : {
          latitude : pos.coords.latitude,
          longitude : pos.coords.longitude
        }
      }
    };
this.pickLocationHandler(coordsEvent);

   },
   err => {
     console.log(err);
     alert("Fetching the position failed,Please pick one manually")
   })
 }

推荐答案

您需要将位置保留在状态上,并在您的组件安装时要求它.使用 react-native-maps,获取位置是一项异步任务,因此您将需要这样的解决方案:

You need to keep the location on the state and ask for it when your component is mounted. With react-native-maps, getting the location is an async task, so you will need a solution like this :

constructor(props){
    super(props);
    state = {
        myLocation: null
    };
}

componentDidMount = () => {
    this.getMyLocation();
};

getMyLocation = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
        this.setState({
            myLocation: 'Permission denied',
        });
    }
    let location = await Location.getCurrentPositionAsync({});
    this.setState({
        myLocation: JSON.stringify(location)
    });
};

Oooooooor 你可以用谷歌搜索

Oooooooor you could have googled

react-native-maps 获取当前位置

react-native-maps get current location

并发现了这个github问题:https://github.com/react-community/react-native-maps/issues/1183

And found this github issue: https://github.com/react-community/react-native-maps/issues/1183

顺便感谢 github 问题的答案.干杯维韦克布拉达!

Credits to the github issue's answer by the way. Cheers Vivekburada !

这篇关于在 Reactnative 中自动获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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