问题
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