I'm using airbnb's map for react-native on my app. This question is for the android app since I didn't get around the iOS app yet.
My problem:
navigator.geolocation works fine on emulator, but takes too long on real devices, to the point it sometimes times out on older devices.
What I've noticed:
if showsUserLocation
prop is set to true, I can see the native "current position" marker on the map way before getCurrentPosition resolves.
What I want:
showsUserLocation
prop, but it seems once watchPostion errors, it stops completely.Here's what I have so far, it's very simple as it is:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("getCurrentPosition Success");
this.setState({
region: {
...this.state.region,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
}
});
this.props.resetNotifications();
this.watchPosition();
},
(error) => {
this.props.displayError("Error dectecting your location");
alert(JSON.stringify(error))
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
}
watchPosition() {
this.watchID = navigator.geolocation.watchPosition(
(position) => {
console.log("watchPosition Success");
if(this.props.followUser){
this.map.animateToRegion(this.newRegion(position.coords.latitude, position.coords.longitude));
}
},
(error) => {
this.props.displayError("Error dectecting your location");
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
}
Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.
I have always found watchPosition
iffy between different browsers, one thing that worked for me before is to replace with getCurrentPosition
inside a setInterval
so that it will get the location every few seconds, and if it fails once it will retry next interval, unlike watchPosition
which stops watching if an error occurs.
Generally browser geolocation is not very reliable, you can check this thread for some issues https://github.com/facebook/react-native/issues/7495
Another alternative which will definitely be faster and maybe more reliable is to use the native geolocation API. Check this question for libraries that expose native geolocation for react native React-native Android geolocation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With