React Native : react-native-geolocation - android

I need to fetching location in react-native. I used #react-native-community/geolocation.
When getCurrentPosition we have option enableHighAccuracy.
My problem is when I run my app in android emulator it must change to enableHighAccuracy: true.
But when I run on device it not working and must be change to enableHighAccuracy : false
This is example of my code :
const callLocation = () => {
setLoading(true);
Geolocation.getCurrentPosition(position => {
const { longitude, latitude } = position.coords
setLoading(false);
setRegion({ ...region, latitude, longitude });
},
error => console.log(error.message),
{
timeout: 20000,
enableHighAccuracy: true, // must change to false when run on device
maximumAge: 1000 },
);
}
Maybe you have the same problem with me, I appreciate a lot about your help.

Finally I solved this problem with storing enableHighAccuracy to state, so whenever the value for instance false is not working I update the value to true and vice versa.
const [enableHighAccuracy, setEnableHighAccuracy] = useState(true); // my state
const callLocation = () => {
setLoading(true);
Geolocation.getCurrentPosition(position => {
const { longitude, latitude } = position.coords
setLoading(false);
setRegion({ ...region, latitude, longitude });
},
error => {
setEnableHighAccuracy(!enableHighAccuracy); // change when error
console.log(error.message)
},
{
timeout: 20000,
enableHighAccuracy, // apply the state to this
maximumAge: 1000 },
);
}

Related

React-Native-Geolocation-Service not giving appropiate latitude and longitude

The latitude and longitude provided by React-native-geolocation-service is not changing even changing location from Noida to Ghaziabad.
I have create two different Alerts one in getlocation method and another in watchposition method. The current Alert (that is in getLocation method) and changed alert (that is present in watchposition method) I get to know that the latitude and longitude provided by React-native-geolocation-service is not as per accuracy.
Here is the method that are working for geolocation to getCurrentPosition and to watchPosition whenever user changes position.
const getOneTimeLocation = () => {
setLocationStatus("Getting Location ...");
Geolocation.getCurrentPosition(
(position) => {
setLocationStatus("You are Here");
Alert.alert("current"," latitude "+ JSON.stringify(position.coords.latitude)+ " Longitude "+ JSON.stringify(position.coords.longitude))
setCurrentLatitude(JSON.stringify(position.coords.latitude));
setCurrentLongitude(JSON.stringify(position.coords.longitude));
// weather(false,position.coords.latitude,position.coords.longitude)
console.log(currentLatitude,currentLongitude,"dekhooooo")
// setCurrentLatitude(currentLatitude);
},
(error) => {
setLocationStatus(error.message);
Alert.alert(error.message);
},
{
enableHighAccuracy: true,
timeout: 30000,
maximumAge: 1000,
}
);
};
``````````````````````````````````````````````````````````````````````````````````````````````````````````
const watchPositionMethod = () => {
watchID = Geolocation.watchPosition(
(position) => {
setLocationStatus("You are Here");
console.log(position);
Alert.alert("Changed"," latitude "+ JSON.stringify(position.coords.latitude)+" Longitude "+ JSON.stringify(position.coords.longitude))
setCurrentLatitude(JSON.stringify(position.coords.latitude));
setCurrentLongitude(JSON.stringify(position.coords.longitude));
// Alert.alert()
},
(error) => {
setLocationStatus(error.message);
Alert.alert(error.message);
},
{
enableHighAccuracy: true,
maximumAge: 1000,
}
);
};
`````````````````````````````````````````````````````````````````````````````````````````````````````````

React Native Geolocation await function not working

I am trying to get geolocation from the react-native package "#react-native-community/geolocation". on button click I want to get latitude and longitude, for that, I am creating a separate function called getUserCurrentLocation() but I want to make this function as async-await type.
const getUserCurrentLocation = () async => {
await Geolocation.getCurrentPosition(
info => {
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);
},
error => console.log(error),
{
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 10,
distanceFilter: 0,
},
);
};
You need to move async behind the parentheses. that's how to use async and await with try and catch block
const getUserCurrentLocation = async () => {
try {
const info = await Geolocation.getCurrentPosition();
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);
} catch(error) {
console.log(error);
}
};
but I saw on Documents you don't need to use a promise the is an example and it should work normally:
Visit https://github.com/react-native-geolocation/react-native-geolocation/blob/master/example/GeolocationExample.js#:~:text=componentDidMount()%20%7B-,Geolocation.getCurrentPosition(,)%3B,-this.watchID%20%3D%20Geolocation
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);

GPS location fluctuating in react native

I am using GPS location in one of my app in react native. I need to track user location at some intervals. but I am getting different latitude and longitude. I have already set it for high accuracy. But it does not return the accurate location of the user. Also, I found GPS return different locations in IOS and Android. Please help me with how I can get exact location of the user.
I am facing this problem a while ago, this core geolocation api doesn't work perfectly on real devices even you using the HighAccuracy flag true, so here i have found some lib which you can use in order to get exact location
react-native-geolocation-service
Here is my code which I have used with above lib, have tested with both IOS and android Devices
import Geolocation from 'react-native-geolocation-service'
This function used to get current location of use
const getUserCorrectLocation = async () => {
await Geolocation.getCurrentPosition(
currentLocation => {
const { coords } = currentLocation
},
error => {
console.log(error, 'error')
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000, distanceFilter: 0,
forceRequestLocation: true }
)}
Second function that I have used is to track user location when he
start his journey
useEffect(() => {
const watchId = Geolocation.watchPosition(
position => {
const { coords } = position
},
error => {
console.log(error, 'coords')
},
{
enableHighAccuracy: true,
interval: 2000,
fastestInterval: 1000,
distanceFilter: 2
}
)
return () => Geolocation.clearWatch(watchId)
}},[])

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