Aditya
Aditya

Reputation: 53

To get Current Location Automatically in 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")
   })
 }

Upvotes: 0

Views: 6389

Answers (1)

R.Duteil
R.Duteil

Reputation: 1227

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 !

Upvotes: 2

Related Questions