在Reactnative中自动获取当前位置

时间:2018-10-09 06:39:14

标签: react-native react-native-android react-native-maps

我有这种方法可以通过单击按钮来获取当前位置,它将获取当前位置。我想获取位置而不单击该按钮。

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

1 个答案:

答案 0 :(得分:1)

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

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

哦,你可以谷歌搜索

  

react-native-maps获取当前位置

并发现以下github问题:https://github.com/react-community/react-native-maps/issues/1183

顺便说一下,对github问题的答案表示感谢。干杯Vivekburada!

相关问题