I think you can use
navigator.geolocation.getCurrentPosition(
(position) => {
//do stuff with location
},
(error) => {
this.setState({locationEnabled: false}),
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
For opening settings from your app, I think you will have to get your hands dirty with native code :D
Answer from Aakash Sigdel on Stack Overflow
» npm install react-native-android-location-enabler
I think you can use
navigator.geolocation.getCurrentPosition(
(position) => {
//do stuff with location
},
(error) => {
this.setState({locationEnabled: false}),
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
For opening settings from your app, I think you will have to get your hands dirty with native code :D
Update:
The error no location provider is available is thrown when GPS is not enabled its error code value is 2.(log the error.message or code if you want to be sure).
const NO_LOCATION_PROVIDER_AVAILABLE = 2;
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({ position });
},
(error) => {
if (error.code === NO_LOCATION_PROVIDER_AVAILABLE) {
//Show alert or something here that GPS need to turned on.
}
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
android - Checking if location services are enabled using react native - Stack Overflow
[expo] Alert user when he disabled GPS location sharing while using app
ios - Determining if geolocation enabled with react native - Stack Overflow
How to know when GPS was enabled?
Videos
Use the "react native android location services dialog box" module for android
https://www.npmjs.com/package/react-native-android-location-services-dialog-box
install
npm install react-native-android-location-services-dialog-box --save
js
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";
LocationServicesDialogBox.checkLocationServicesIsEnabled({
message: "Use Location ?",
ok: "YES",
cancel: "NO"
}).then(function(success) {
console.log(success); // success => "enabled"
).catch((error) => {
console.log(error.message); // error.message => "disabled"
});
Do a watchPosition or getCurrentPosition, Your second argument is a callback in case of failure, and its argument is the reason it failed.
So, from there you know when and why it fails. You'll need an if for the reason if you only want to act on 'location disabled' and not 'request timed out' for example.
You can use the callback to add a flag to your state for example.
I'm building an expo google maps based app. I'm monitoring the user's location with watchPositionAsync() . I want to alert the user that he needs to enable location sharing if he disables it while using the app. Just like in google maps navigation.
So if I'm following a tour and if I disable location sharing from the mobile dropdown for example, I want to prompt an alert to enable it, because without the user's current location the navigation should not work.
The problem with this code is :
-
When I first time come to this component and I accept location sharing, then later if I disable location sharing while using the app, I don't get an alert. I need to use
setLocationEnabled(true);somewhere but I don't know where -
When I first come to this component and decline location sharing the first time, then if I enable location sharing again it won't get detected.
import React, { useState, useEffect } from "react";
import { Alert, StyleSheet, Text, View } from "react-native";
import * as Location from "expo-location";
export default function App() {
const [location, setLocation] = useState(null);
const [watchId, setWatchId] = useState(null);
const [locationEnabled, setLocationEnabled] = useState(false);
useEffect(() => {
(async () => {
await Location.hasServicesEnabledAsync();
setLocationEnabled(true);
console.log("location enabled");
})();
}, []);
useEffect(() => {
Location.watchPositionAsync(
{
accuracy: Location.Accuracy.Highest,
distanceInterval: 1,
timeInterval: 10000,
},
(pos) => {
setLocation(pos.coords);
}
)
.then((locationWatcher) => {
//set locationwatcher for removing
setWatchId(locationWatcher);
})
.catch((err) => {
setLocationEnabled(false);
console.log("watchpositon error: ", err.message);
});
return () => {
watchId && watchId.remove();
};
}, []);
useEffect(() => {
if (!locationEnabled) Alert.alert("You need to enable location sharing");
}, [locationEnabled]);
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{JSON.stringify(location)}</Text>
</View>
);
}Can somebody please help me? I've been stuck at this for days and haven't found any similar questions/answers.
» npm install react-native-location-enabler
You can use this library https://github.com/yonahforst/react-native-permissions to check if user has accepted location permission. Like this:
Permissions.getPermissionStatus('location')
.then(response => {
this.setState({ locationPermission: response })
})
In v2.x.x of react-native-permissions (https://github.com/react-native-community/react-native-permissions)
import { Platform } from "react-native";
import { PERMISSIONS, request } from "react-native-permissions";
import * as Geolocation from "@react-native-community/geolocation";
try {
request(
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
})
).then(res => {
if (res == "granted") {
Geolocation.getCurrentPosition( // do location staffs);
Geolocation.watchPosition( // do watch location staffs );
} else {
// console.log("Location is not enabled");
}
});
} catch (error) {
console.log("location set error:", error);
}
So I am going to start answering my own question.
For GPS:
there seems to be a sensible solution. IOS seems to natively request if there is a geolocation request. And for Android this is not natively supported but someone has created a module for that ( https://github.com/webyonet/react-native-android-location-services-dialog-box )
so in my action creator I added the next code:
if(Platform.OS === 'android')
LocationServicesDialogBox.checkLocationServicesIsEnabled({
message: "<h2>Use Location?</h2> \
This app wants to change your device settings:<br/><br/>\
Use GPS for location<br/><br/>",
ok: "YES",
cancel: "NO"
}).then(() => {
locationTracking(dispatch, getState, geolocationSettings)
})
For Network: There is no native support for neither so i end up doing my own action creator to check.
export function networkCheck(){
return (dispatch) => {
const dispatchNetworkState = (isConnected) => dispatch({
type: types.NETWORK_STATE,
state: isConnected
})
const handle = () => NetInfo.isConnected.fetch().done(dispatchNetworkState)
NetInfo.isConnected.addEventListener('change', handle);
}
}
A little extra:
for GPS i added this to check if the user goes and disable GPS on the middle of the task.
export function locationCheck(geolocationSettings = {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000, distanceFilter:10}){
return (dispatch) => {
navigator.geolocation.watchPosition(
() => {
dispatch({
type: types.LOCATION_STATE,
state: true
})
},
() => {
dispatch({
type: types.LOCATION_STATE,
state: false
})
},
geolocationSettings)
}
}
For enabling location/gps on Android I can recommend this module: https://github.com/Richou/react-native-android-location-enabler
It is using the standard Android dialog for location:

» npm install @react-native-community/geolocation
» npm install react-native-location-settings-enabler
» npm install react-native-android-location-services-dialog-box
