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 },
);
}
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)
}},[])
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.
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:
In IOS there isn't a problem while looking for gps coords. It works fine.
On Android side its not stable as IOS. This problem both in real device and emulator. Sometimes it can find location, but sometimes not. Looking for 3days but there wasn't find a solution.
When my app cannot find my location, I tried via Google Maps app, it works like charm.
Here is my code for both IOS and Android;
getCurrentPosition() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({ initialPosition: position });
alert(JSON.stringify(position))
var coords = new Coords();
coords.Latitude = position.coords.latitude;
coords.Longitude = position.coords.longitude;
this.getPharmaciesByCoordinates(coords);
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
this.watchID = navigator.geolocation.watchPosition((position) => {
this.setState({ initialPosition: position });
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
Any kind of solution is welcome.
Thanks
I removed maximumAge: 3600000 on Android and it working
It's possible that you are inside of the building or office and your signal is not that good. I've tried with many configuration and this one fit the best for me:
{
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 10000
}
Or try increasing timeout. Because for me the usual 2000ms wasn't working, I kept getting "Location request timed out". So disable high accuracy, increase timeout and you're good to go.
import Geolocation from '#react-native-community/geolocation';
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
console.log(initialPosition);
},
error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);
This function work for me and I have change the "AndroidManifest.xml" file with the
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Hi I was facing same issue "request time out ".
I have tried every possible solution which I found but, those could not work for me but recently I found one module which overcomes this problem.
react-native-geolocation-service
This worked for me .....
For those who still facing the issue, be aware of the params. I used to leave params to defaults but when it comes to enableHighAccuracy, you should be careful because when you set this to false, that means you are requesting WIFI location else GPS location. If you don't set this true, you will probably receive error on emulators as I did.
Supported options:
timeout (ms) - Is a positive value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. Defaults to INFINITY.
maximumAge (ms) - Is a positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device will always return a cached position regardless of its age. Defaults to INFINITY.
enableHighAccuracy (bool) - Is a boolean representing if to use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested.
Detailed Documentation
Edit 1;
I recommend you all to use this library instead of native one (react-native-geolocation-service) as its created for such timeout issues.
Remove Param 'maximumAge' & Just Keep
{ enableHighAccuracy: true, timeout: 2000}
I found a solution via external lib that uses native LocationManager. It uses play services location and emitting location event as I want.
Here is the library;
https://bitbucket.org/timhagn/react-native-google-locations#readme
And when compiling for android, don't forget to include android/app/build.gradle
dependencies {
...
compile "com.google.android.gms:play-services:10.0.1" -> which version that you have write down here.
...
}
And finally don't forget to download Google Play Services and Google Support Library in Android SDK Manager you can find your play services versions into;
<android-sdk-location>/<sdk-version>/extras/google/m2repository/com/google/android/gms/play-services
I have done the app by location request. The command
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }, will work on iOS but not in Android. I think you should check Platform.
navigator.geolocation.getCurrentPosition(
(location) => {
console.log('location ', location);
if (this.validLocation(location.coords)) {
this.locationToAddress(location.coords);
}
},
(error) => {
console.log('request location error', error);
},
Platform.OS === 'android' ? {} : { enableHighAccuracy: true, timeout: 20000, maximumAge: 10000 }
);
I tried various methods and npm modules. Finally I got solved this issue by using this module. I strongly suggest this.
https://www.npmjs.com/package/react-native-geolocation-service
In my case it worked fine after removing timeout and maximumAge and setting enableHighAccuracy to false.
Working
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add Permission in P list and android Manifest also
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },
// { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</View>
);
}
}
I suggest to 2 ways to consider dealing with it:
Use react-native-geolocation-service - a package that suppose to deal with that problem.
Try to call once with enableHighAccuracy=true and if it fails try to call it again with enableHighAccuracy=false.
Details: It seems enableHighAccuracy=true try fetching the location via the GPS - when enableHighAccuracy=false the device first try fetching the location via Wifi and if it fails it try to fetch it via the GPS.
Here is how I've implemented number 2:
import Geolocation from "#react-native-community/geolocation";
const getCurrentLocation = (resolve, enableHighAccuracy, onError) => {
console.log(`[getCurrentPosition] enableHighAccuracy=${enableHighAccuracy.toString()}`);
Geolocation.getCurrentPosition(
(position) => {
const location = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
console.log('[getCurrentPosition] success');
resolve(location);
},
onError,
{enableHighAccuracy, timeout: 20000}
);
};
/**
* We first try to get location with enableHighAccuracy=true (try to get position via GPS) if it fails try to get it with enableHighAccuracy=false (try to get position from wifi)
* #return {Promise}
*/
export const getCurrentPosition = () => {
return new Promise((resolve) => {
getCurrentLocation(resolve, true,
(error1) => {
// failed to retrieve with enableHighAccuracy=true - now try with enableHighAccuracy=false
console.log(`[getCurrentPosition] failed 1st time trying again with enableHighAccuracy=false, error: ${error1.message}`);
getCurrentLocation(resolve, false, (error2) => {
// Could not retrieve location - we can live with that
console.log(`[getCurrentPosition] failed ${error2.message}`);
resolve();
})
});
});
}
i was stuck for 3 days but all in vain then
i just change timeout to value 20000ms.
now problem is resolved.
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 20000,
just change/Increase "timeout" value your problem will resolve.
You might want to check if your android emulator GPS is enabled or not.
Go to options ( "⋮" on emulator) --> Location --> Enable GPS signal should be enabled.
Removing timeout and maximumAge did solve the issue on android on my end
the tricks is, if you set
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }
then it will work. full code below.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class GeolocationExample extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 },
);}
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</View>
);
}
}
export default GeolocationExample;