React Native Geolocation await function not working - android

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},
);

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 : react-native-geolocation

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 },
);
}

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