To get Current Location Automatically in Reactnative
Asked Answered
H

1

0

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")
   })
 }
Heraclitean answered 9/10, 2018 at 6:39 Comment(2)
Do you want to get the location on a periodic basis ? After a particular event ?Legit
I want to display current location when map screen opensHeraclitean
L
2

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 !

Legit answered 9/10, 2018 at 7:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.