GeoLocation React Native - android

I am trying to get the user location my code is working fine in the
ios and in the android it does not throw the error when user denies
the location permission.
AppState.addEventListener('change', this._handleAppStateChange);
this.geoFailure, geoOptions);
this.refresh();
}
geoSuccess = (position) => { //Success callback when user allow the
location
this.setState({
ready:true,
where: {lat:
position.coords.latitude,lng:position.coords.longitude }
})
}
geoFailure = (err) => { // i am not getting any error when user
denies the location permission in the
case of android.
this.setState({error: err.message});
console.log("Errror",err)
console.log(err.message)
if(err.message='User denied access to location services'&&Platform.OS==='ios'){
this.props.screenName==='SPLASH'&&!this.state.ready?NavigatorService.navigate(LOCATION_PERMISSION):null;
}
}
refresh=()=> // Refreshing the list when the AppState becomes
active
let geoOptions = {
enableHighAccuracy: false,
timeout: 30000,
maximumAge: 60 * 60 * 24
};
this.setState({ready:false, error: null });
navigator.geolocation.getCurrentPosition( this.geoSuccess, this.geoFailure, geoOptions);
}
I am able to navigate the user to another screen in the case of ios
if it doesn't provide the location permissions but in the case of
the android it does not giving any error when user does not provide
the location.
I am not getting how to do it , i am new to the react native.
I am not getting, what i am doing wrong.
Any help would be appreciated.

use PermissionsAndroid
import {
PermissionsAndroid
} from 'react-native';
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
(position) => {
addLocation(position.coords);
},
(error) => {
console.error(error);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 },
);
} else {
console.log('location permission denied');
}

Related

Error using Expo SDK 42: [Unhandled promise rejection: Error: Location provider is unavailable. Make sure that location services are enabled.] Android

I have enable location services on my Android device, but I keep getting the above error. It prompts me for my permissions request upon loading Expo (for the first time) but I still get the promise rejection. It used to work fine, but all of a sudden, stopped working. Below is my code requesting the permissions, and executing the location.
Note: This works fine on iOS, and this is in managed workflow.
useFocusEffect(
React.useCallback(()=> {
let isActive = true;
async function getLocationAsync() {
let { status } = await Location.requestForegroundPermissionsAsync()
if (status !== 'granted'){
setErrorMsg('Permission to access location was denied')
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
console.log('Location permissions granted')
}
console.log(location)
getLocationAsync()
console.log(Permissions.LOCATION)
console.log('Location status above')
return () =>{
isActive = false
}
},
[],
)
)
Call the function in the catch block until you get the coordinates.
getLocationAsync = async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
this.setState({
errorMessage: 'Permission to access location was denied',
});
console.log('Permission to access location was denied')
}else{
try{
let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true });
const { latitude, longitude } = location.coords
});
}catch(error){
// Call the function until get the coordinates
this.getLocationAsync();
}
}

How to avoid "Sending 'geolocationDidChange' with no listeners registered" warning in react native?

I am going to get current location in react native.
I was used below code:
if(Platform.OS == "android") {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location Permission',
'message': 'Wichz would like to access your location to get your things.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// console.warn("You can use locations ")
} else {
// console.warn("Location permission denied")
}
} catch (err) {
// console.warn(err)
}
}
this.watchID = navigator.geolocation.watchPosition((position) => {
this.setState({
selectedLat: position.coords.latitude,
selectedLng: position.coords.longitude
});
Global.selectedLat = position.coords.latitude;
Global.selectedLng = position.coords.longitude;
this.getcurrent_address(position.coords.latitude, position.coords.longitude);
}, (error)=>console.log(error.message),
{enableHighAccuracy: false, timeout: 3, maximumAge: 1, distanceFilter: 1}
);
And add Location usage description like below in ios project:
It works well on both ios and android, but I have get warning box like below:
How can avoid this warning box? Thanks
It's probably too late now but I'll just detail my experience with this warning for those people in the future that have this same issue.
I encountered this error myself before. For me the cause of this warning is basically that the component is re-rendered before geolocation watchPosition call is fully completed.
In my case, it was because I had multiple fetch calls that caused the component to be re-rendered in quick succession. I fixed it by making geolocation watchPosition only be called on the final render of the component.

Mock GPS location on android hardware - React Native

I have tried using applications like 'Fake GPS' and enabled Mock Locations in developer options to mock location. My location is successfully changed on google maps but the react native geolocation.getCurrentPosition is still returning me my actual true location.
Also, when calling geolocation.getCurrentPosition after different interval I'm getting response with the same timestamp. What's the reason?
getLocation() {
navigator.geolocation.getCurrentPosition(
position => {
if (this.state.inRide === false) {
console.log('setting start coord');
this.setState(
{ startLat: position.coords.latitude, startLong: position.coords.longitude },
() => this.afterStartLocationSuccess()
);
} else if (this.state.inRide === true) {
console.log('setting end coord');
this.setState(
{ endLat: position.coords.latitude, endLong: position.coords.longitude },
() => this.afterEndLocationSuccess()
);
}
console.log(position);
},
error => Alert.alert('Try again! GPS not working')
// Not using third argument.
// { enableHighAccuracy: false, timeout: 10000, maximumAge: 1000 }
);
}
This is the console log:

React native geolocation getCurrentPosition no reponse (android)

I have read and tested a lot of issues but I still can not get geolocation on Android.
I use navigator.geolocation.getCurrentPosition, on iOS everything works fine, but on Android I have no answer to this function, either success or error.
I have installed react-native-permissions to make sure that the user has activated the permissions but it does not change anything because it says that everything is "authorized".
I noticed that it came from GPS of the device. If I activate it manually, everyting works fine. However, I can not find a way to activate it for the user. On iOS, if GPS is not activated, I fall in the error callback and tell user to activate it, but on android, nothing is happennig.
I don't understand why I can't get geolocation only with getCurrentPosition (I have ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in manifest).
Here a part of my code:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
//do my stuff with position value
},
(error) => {
Permissions.getPermissionStatus('location')
.then((response) => {
if (response !== "authorized") {
Alert.alert(
"Error",
"We need to access to your location",
[
{
text: "Cancel",
onPress: () => {
// do my stuff
}, style: 'cancel'
},
{
text: "Open Settings",
onPress: () => Permissions.openSettings()
}
]
);
} else {
// do my stuff
}
});
},
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 }
);
}
Does anyone have any idea ?
Thank you
You should need to enable GPS on android
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:
like this
import React, { Component } from "react";
import { Text, StyleSheet, View, Platform } from "react-native";
import RNAndroidLocationEnabler from "react-native-android-location-enabler";
export default class index extends Component {
componentDidMount() {
this.getLocation();
}
onLocationEnablePressed = () => {
if (Platform.OS === "android") {
RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({
interval: 10000,
fastInterval: 5000,
})
.then((data) => {
this.getLocation();
})
.catch((err) => {
alert("Error " + err.message + ", Code : " + err.code);
});
}
};
getLocation = () => {
try {
navigator.geolocation.getCurrentPosition(
(position) => {
//do my stuff with position value
},
(error) => {
Permissions.getPermissionStatus("location").then((response) => {
if (response !== "authorized") {
Alert.alert("Error", "We need to access to your location", [
{
text: "Cancel",
onPress: () => {
// do my stuff
},
style: "cancel",
},
{
text: "Open Settings",
onPress: () => Permissions.openSettings(),
},
]);
} else {
// do my stuff
}
});
},
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 }
);
} catch (error) {
this.onLocationEnablePressed();
}
};
}

React Native GeoLocation is not working on Android

Can anyone confirm if React Native Geolocation is actually working on Android?
I am stuck with location request timed out while using getCurrentPosition() method and no error message while using watchPosition() method.
I have added the required permission (FINE LOCATION) on AndroidManifest.xml and location permission is allowed for the app.
Here is my implementation:
componentWillMount() {
navigator.geolocation.getCurrentPosition((position) => {
console.log('+++++++');
console.log(position.coords.longitude);
this.setState({
longitude: position.coords.longitude,
error: null,
});
},
(error) => {
console.log(error);
},
);
}
React Native Version : 0.42
you need to change enableHighAccuracy to false
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
this.state = {
region:{}}
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
region: {
longitude: position.coords.longitude,
latitude: position.coords.latitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}
});
},
(error) => console.log(new Date(), error),
{enableHighAccuracy: false, timeout: 10000, maximumAge: 3000}
);
After implementing all above answers
i had to restart my new phone then it started working
Yes, location works perfectly in our React Native apps for Android.
First of all, getCurrentPosition(..) does not return a watchId. You should be using watchPosition(..) for that. Check that your device has location services enabled and if you're testing it in the emulator, that you've set a location in emulator settings. Another note: on Android M and higher, you also need to request permissions using the PermissionsAndroid.check(...) and PermissionsAndroid.request(...) API calls.
Instead of referring to the position object, just deal with the coords object.
navigator.geolocation.getCurrentPosition(
({coords}) => {
const {latitude, longitude} = coords
this.setState({
position: {
latitude,
longitude,
},
region: {
latitude,
longitude,
latitudeDelta: 0.001,
longitudeDelta: 0.001,
}
})
},
(error) => alert(JSON.stringify(error)),
// 'enableHighAccuracy' sometimes causes problems
// If it does, just remove it.
{enableHighAccuracy: true}
)
I had a similar issue to this because I was in a building which resulted to my device not being able to properly capture the gps signals. If you are in a closed building, try moving outside.
My advise to get perfect location data is to create 2 location handlers.
I use react-native-location as a first handler,
if location cant be fetched, we use the second handler using native geolocation.
Never fails, Compability:
IOS - all versions
ANDROID - all above SDK 20
Check the example below:
Configuration
RNLocation.configure({
distanceFilter: 0.5,
desiredAccuracy: {
ios: "best",
android: "highAccuracy"
},
headingOrientation: "portrait",
// Android ONLY
androidProvider: "auto",
interval: 5000, // Milliseconds
fastestInterval: 10000, // Milliseconds
maxWaitTime: 5000, // Milliseconds
// IOS ONLY
allowsBackgroundLocationUpdates: false,
headingFilter: 1, // Degrees
pausesLocationUpdatesAutomatically: false,
showsBackgroundLocationIndicator: false,
})
Function getUserLocation
static getUserLocation = async () => {
let locationSubscription: any = null
let locationTimeout: any = null
const options = { enableHighAccuracy: true, timeout: 25000 }
return new Promise<any>((resolve, reject) => {
// request permissions using RN Location
RNLocation.requestPermission({
ios: "whenInUse",
android: {
detail: "fine"
}
}).then(granted => {
console.log("Location Permissions: ", granted)
// if has permissions try to obtain location with RN location
if (granted) {
locationSubscription && locationSubscription()
locationSubscription = RNLocation.subscribeToLocationUpdates(([locations]: any) => {
locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("location fetched with RN Geolocation")
resolve({ coords: { latitude: locations.latitude, longitude: locations.longitude }})
})
} else {
locationSubscription && locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("no permissions to obtain location")
resolve(null)
}
// if RN Location cant resolve the request use Native Location instead
locationTimeout = setTimeout(() => {
navigator.geolocation.getCurrentPosition((locations) => {
locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("location fetched with Native Geolocation")
resolve(locations)
}, error => {
locationSubscription && locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("location error", error)
resolve(null)
}, options);
}, 15000)
})
})
}
cd android
gradlew clean
dependencies
"react-native": "0.62.0",
"#react-native-community/geolocation": "^2.0.2",
Better if you try this code, I have tested in Android OS 8, RN 0.49.5
React Native current location
the trick is to set
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }

Categories

Resources