React native location when device's location in turned off - android

My android app crashes if device's location is turned off when I request permission to get location . how can I fix this? here is my getLocation() function:
getLocation = () => {
try {
navigator
.geolocation
.getCurrentPosition(position => {
const location = JSON.stringify(position);
this.writeItemToStorage(position.coords.latitude,position.coords.longitude);
this.setState({location: location, latitude: position.coords.latitude, longitude: position.coords.longitude});
}, error => Alert.alert(error.message), {
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 10000
});
} catch(e) {
alert(e);
}
}
I set the lat and long in asyncstorage

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

how to get live geo location in react native

I've added MapView into my app but i want to initialize the region with the current user's live location, The code on the emulator changes the initial region to the location of google's HQ in CA (I know that's normal and i can change the emulator's location in settings) but on my own phone, the initial region doesn't change at all.
using the GEO location api preferred by react native:
const [region, setRegion] = useState({
latitude: -1.951670,
longitude: 30.157518,
latitudeDelta: 0.015,
longitudeDelta: 0.015,
})
useEffect(() => {
let currentLocation = true;
let newRegion = { latitude: null, longitude: null, latitudeDelta: null, longitudeDelta: null };
newRegion.longitudeDelta = region.longitudeDelta;
newRegion.latitudeDelta = region.latitudeDelta;
Geolocation.getCurrentPosition((info) => {
newRegion.latitude = info.coords.latitude
newRegion.longitude = info.coords.longitude;
},
(error) => {
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
)
//To make sure no null is still present in the newReion obj
for (var key in newRegion) {
if (!newRegion[key]) {
currentLocation = false;
break;
}
}
if (currentLocation) {
setRegion(newRegion);
}
}, [])
//Map view implementation:
<MapView
provider={PROVIDER_GOOGLE}
ref={map => _map = map}
showsUserLocation={true}
style={styles.map}
initialRegion={initialPosition}
onRegionChangeComplete={(region) => setInitialPosition(region)}
/>

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