To get Current Location Automatically in Reactnative

风流意气都作罢 提交于 2019-12-11 16:51:44

问题


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

回答1:


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 you could have googled

react-native-maps get current location

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

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



来源:https://stackoverflow.com/questions/52714737/to-get-current-location-automatically-in-reactnative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!