Device GPS configuration in react-native - android

I'm developing a react-native app and I want to check that if the GPS of device is on do something and if the device's GPS is off, tell the user and request him to turn it on. So my question is:
How can I check that the GPS of device is on?
How can I redirect the user to GPS setting page?
I want to do these without adding any new package to project.

My problem is solved. I should use the error code of the getCurrentPosition function. If error code equals 1, it means that the GPS of device is off.
navigator.geolocation.getCurrentPosition(
(position) => {
...
},
(error) => {
if (error.code === 1) {
// gps is off
}
...
},
{enableHighAccuracy: false, timeout: 10000},
)

Related

Bad/poor GPS location accuracy on Android with React Native

I am working on a React Native app that works both on Android and iPhone. I have a feature where you can "share my current location". This works very well and accurately on iPhone but on Android, it only shows the correct city/locality however the actual location is far off from your street. For getting the location I use the https://github.com/Agontuk/react-native-geolocation-service library.
Here's the relevant code, I'm simply calling Geolocation.getCurrentPosition, not doing anything special. And I'm asking for high accuracy in options. Any ideas on how I can improve the accuracy on Android?
Edit: If I open Google Maps on the same Android phone, I get the accurate/correct location.
Geolocation.getCurrentPosition(
(position) => {
// Do stuff with the position
},
(error) => {
// See error code charts below.
logError(
new Error(
`Cannot get current location: ${error.code} ${error.message}`,
),
);
},
{
enableHighAccuracy: true,
accuracy: {
android: 'high',
ios: 'bestForNavigation',
},
timeout: 15000,
maximumAge: 10000,
distanceFilter: 10,
},
);
}
},```
I figured out that the issue was that I did not have the ACCES_FINE_LOCATION permission in my AndroidManifest.xml. It's a bit confusing because this did not result in any actual error, it just did not give accurate location instead.
So just add this to the manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Location tracking in background with PhoneGap

I'm trying to create very simple application that will get the current location of the device and post it to server every 15 minutes or so.
I'm using cordova-plugin-background-fetch ( https://github.com/transistorsoft/cordova-plugin-background-fetch ) and it works just fine awaking the app on about 15 minutes (or so), but the issue I'm facing is to get GPS coordinates.
I'm trying to get it using navigator.geolocation.getCurrentPosition and before I start BackgroundFetch, I make one test call with navigator.geolocation.getCurrentPosition to check if it works and have all the permissions. It is the same code as in example callback function and it works just fine on that first test call.
The problem I'm facing is that once BackgroundFetch awakes the application, in callback function navigator.geolocation.getCurrentPosition always fail (error code 3 - timeout expired).
I even tried to make it work with navigator.geolocation.watchPosition, but same issue. The first time I start it, it works. Once callback start it in background, it fails (again timeout expired).
I don't want to watch position all the time and drain the battery, I really need it only once in every 15-30 minutes.
Here is the code that I'm using and every help and suggestion is welcome!
Thank you!
BackgroundFetch.configure(function() {
console.log('[js] BackgroundFetch event received');
navigator.geolocation.getCurrentPosition(function(position){
console.log('we have location now');
$.post('https://www.example.com/api/location/', {
Lat: position.coords.latitude,
Lon: position.coords.longitude
}, function(data){
window.BackgroundFetch.finish();
}, 'json').fail(function(){
window.BackgroundFetch.finish();
});
}, function(error){
console.log('Error code: ' + error.code);
console.log('Error message: ' + error.message);
window.BackgroundFetch.finish();
}, {
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 0
});
}, function(error) {
console.log('- BackgroundFetch failed', error);
}, {
minimumFetchInterval: 15
});
I thin the problem is the user has to physically accept geo location services one for them to be fetched

react native navigator.geolocation.getCurrentPosition not working

I am using a real android device (version 5.1)
I am able to determine my position using react-native-maps (correct blue point position on map inside my app ) + I am able use google maps app and go to my position (GPS works).
I am using a big timeout, toggling enableHighAccuracy to true and false, remove options ... etc . all failed to get navigator.geolocation to get data.
Here is my code:
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
};
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
};
navigator.geolocation.getCurrentPosition(success, error, options);
I am getting : ERROR(3): Location request timed out
I know it's too late, but it can help someone else.
Geolocation has been extracted from react native .60 version. If you need an alternative solution
Install react-native-community/geolocation :
npm install #react-native-community/geolocation --save
react-native link #react-native-community/geolocation
Then, to request access to location, you need to add the following line to your app's AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Usage :
import Geolocation from '#react-native-community/geolocation';
Geolocation.getCurrentPosition(info => console.log(info));
Two things.
1) That is actually not a high timeout for a high accuracy response if the coordinates are not cached
2) Some devices have problems with the highAccuracy setting.
Try putting 30000 ms as timeout and remove the high accuracy until you find one setting that works.
Edit: I found the long bug I was remembering form React Native: https://github.com/facebook/react-native/issues/7495
So, try this:
1) Remove maximumAge property
2) If that does not work, remove the third parameter and use the default values from the native module. Meaning, don't send the options object. That should work.
Removing maximumAge solved the issue here! Just in case someone is still having this problem in 2019 or later
To request access to location, you need to add the following line to your app's AndroidManifest.xml: <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />.
For an android with API >= 23 you need to require an additional step to check for: you need to request the ACCESS_FINE_LOCATION permission using the PermissionsAndroid API.
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Accessing Permission",
message: "App needs access to your location"
}
);
And only after that run navigator.geolocation.getCurrentPosition(success, error, options);
I used this and it works fine: {enableHighAccuracy: false, timeout: 50000}
async watchPosition() {
console.log('watchPosition');
await navigator.geolocation.getCurrentPosition(
(position) => {
console.log('Position -> ',position);
},
(error) => console.log(error)
{enableHighAccuracy: false, timeout: 50000}
);
}

Follow user location on React Native AirBnb's MapView [Android]

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:
I want my region to always be centered on the user's location.
I want either a way to access native geolocation api (should be
faster?), or maybe someone to tell me what I'm doing wrong. Below is
a code sample.
I want to still be able to detect the user's location even after the location services have been toggled on/off. This is the behaviour of the 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}
);
}
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
Not sure if this will solve your issue but try this:
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();
});
},

React native for Android navigator geolocation not running

On my iOS app the geolocation works fine and picks up my location on the watcher function.
However for Android, the code never seems to get executed on the success or fail callbacks when I put in alert's or console logs.
watchID: (null: ?number),
this.watchID = navigator.geolocation.watchPosition(
(position) => {
this.setState({
userLocation: position,
geo: true
}, this.fetchBusinesses());
},
(error) => console.log(error.message),
{enableHighAccuracy: true, timeout: 2000, maximumAge: 1000}
);
If you are running with newest Android, you manual set "Location" to on.
This switch is under Setting -> Apps -> {Your app} -> Permissions.

Categories

Resources