I want to get currentlocation of user , I am getting current location in android and ios but not on android tablet - react-native

I am getting correct latitude and longitude in android and ios and showing the marker but this doesn't happen on tablet. I am not getting marker in tablet android , I have enable showUserLocation={true} as well.
useEffect(() => {
const requestLocationPermission = async () => {
if (Platform.OS === 'ios') {
Geolocation.requestAuthorization('always').then((resp) => {
console.log("ios response ", resp)
Geolocation.getCurrentPosition(
(position) => {
console.log("position:::", position)
const { latitude, longitude } = position.coords;
setCurrentLatitude(latitude)
setCurrentLongitude(longitude)
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 20000 }
);
}).catch((e) => console.log("ios error ::", e))
}
else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Access Required',
message: 'This App needs to Access your location',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
(position) => {
// console.log("position:::", position)
const { latitude, longitude } = position.coords;
setCurrentLatitude(latitude)
setCurrentLongitude(longitude)
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: false, timeout: 20000 }
);
} else {
setLocationStatus('Permission Denied');
}
} catch (err) {
console.warn("Location error ::", err);
}
};
}
requestLocationPermission();
}, [])
This is what I have done

Related

React Native Location Tracker

I'm implementing this code it is showing error like "undefined is not an object (evaluating 'navigator.geolocation.clearWatch')"
watchLocation = () => {
const { coordinate } = this.state;
this.watchID = navigator.geolocation.watchPosition(
position => {
const { latitude, longitude } = position.coords;
const newCoordinate = {
latitude,
longitude,
};
if (Platform.OS === 'android') {
if (this.marker) {
this.marker._component.animateMarkerToCoordinate(newCoordinate, 500); // 500 is the duration to animate the marker
}
} else {
coordinate.timing(newCoordinate).start();
}
this.setState({
latitude,
longitude,
});
},
error => console.log(error),
{
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000,
distanceFilter: 30,
}
);
};
Can anyone let me know how to solve this? Im referring this tutorial.
Link
First install :
npm i #react-native-community/geolocation
Then -
import Geolocation from '#react-native-community/geolocation';
watchLocation = () => {
const { coordinate } = this.state;
this.watchID = Geolocation.watchPosition(
//Your Code
);
}
For reference checkout - https://www.npmjs.com/package/#react-native-community/geolocation
I've gone through the blog which you are following so according to that you'll have to do a change likewise :
componentWillUnmount() {
Geolocation.clearWatch(this.watchID);
}

Why location permission pop up not showing in React Native?

I want to implement get current location in react native. I put permission to activate location if location is not activate in phone before calling geolocation API but pop up not showing and this PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,{ title: 'Location Access Required', message: 'This App needs to Access your location'},); always return "granted" when request permission using PermissionAndroid module.
this is my code
import { PermissionsAndroid } from 'react-native';
import Geolocation from '#react-native-community/geolocation';
...
componentDidMount(){
const requestLocationPermission = async () => {
let geoOptions = {
enableHighAccuracy: true,
timeout:20000,
maximumAge: 60*60*24
}
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Access Required',
message: 'This App needs to Access your location',
},
);
console.warn(granted);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(this.geoLocationSuccess,this.geoLocationFailure,geoOptions);
}
} catch (err) {
console.warn(err);
}
};
requestLocationPermission();
}
is my implementation is wrong ? because i want to show pop up when location service is not enable to let user enable it
This may be of little help, first make sure no library location other than react-native-geolocation-service. then if there is no use react hook. you might try this method below.
hasLocationPermission = async () => {
const hasPermission = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (hasPermission === PermissionsAndroid.RESULTS.GRANTED) {
console.log('lagi req permission');
return true;
}
const status = await PermissionsAndroid.check(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
);
if (status) {
console.log('permission diberikan');
return true;
}
if (status === PermissionsAndroid.RESULTS.DENIED) {
ToastAndroid.show(
'Location permission denied by user.',
ToastAndroid.LONG,
);
} else if (status === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
ToastAndroid.show(
'Location permission revoked by user.',
ToastAndroid.LONG,
);
}
return false;
};
async componentDidMount() {
if (await this.hasLocationPermission()) {
Geolocation.getCurrentPosition(
position => {
console.log('posisi ditemukan',position.coords.latitude, position.coords.longitude);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
this.goToRegion(position.coords.latitude, position.coords.longitude);
},
error => {
Alert.alert(
'Oopss!',
error.message,
[
{
text: 'OK',
onPress: () => console.log('Cancel Pressed'),
},
],
);
console.log(error.message);
this.setState({error: error.message});
},
{
accuracy: {
android: 'high',
ios: 'best',
},
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
distanceFilter: 0,
forceRequestLocation: true,
forceLocationManager: false,
showLocationDialog: true,
},
);
}
}

Add an Event to Expo Calendar?

I'm trying to add an event using Expo Calendar but i'm getting an error. When i call my function openActionSheet the catch block is executed and getting the Alert with the message Error getting device calendars.. When i'm consoling the error i'm getting undefined is not a function (near '...showActionSheetWithOptions...').
My function's code is :
async openActionSheet() {
const { status } = await Permissions.askAsync(Permissions.CALENDAR, Permissions.REMINDERS);
if (status === 'granted') {
Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT)
.then(calendars => calendars.filter(cal => cal.allowsModifications))
.then((calendars) => {
const { showActionSheetWithOptions, navigation } = this.props;
const options = calendars.map(cal => (Platform.OS === 'ios' ? cal.title : cal.source.name)).concat(['Cancel']);
const cancelButtonIndex = calendars.length;
showActionSheetWithOptions({
title: 'Select a calendar:',
options,
cancelButtonIndex,
},
(buttonIndex) => {
const orderId = navigation.getParam('orderId');
const { orderSet } = navigation.getParam('orderSet');
const eventConfig = {
title: `OrderId: ${orderId}` || 'UNKNOWN_NAME',
startDate: new Date(navigation.getParam('orderDate')),
endDate: new Date(navigation.getParam('orderDate')),
location: `${orderSet.location}` || 'UNKNOWN_LOCATION',
notes: '',
};
if (buttonIndex !== cancelButtonIndex) {
Calendar.createEventAsync(calendars[buttonIndex].id, eventConfig)
.then(() => Alert.alert('Success', 'Event has been added to your calendar.'))
.catch(() => {
Alert.alert('Error', 'Event was not saved.');
});
}
});
})
.catch((e) => {
console.log('ERROR');
console.log(e);
Alert.alert('Error', 'Error getting device calendars.');
});
} else {
Alert.alert('Error', 'You have to authorize the application to access your calendar.');
}
}

React native geolocation service not working for iOS

I am trying to get device current position in react native. I am using below library for get the location:
react-native-geolocation-service
My code:
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Device current location permission',
message:
'Allow app to get your current location',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.getCurrentLocation();
} else {
console.log('Location permission denied');
}
} catch (err) {
console.warn(err);
}
}
getCurrentLocation(){
Geolocation.requestAuthorization();
Geolocation.getCurrentPosition(
(position) => {
alert(position.coords.latitude);
this.socket.emit('position', {
data: position,
id: this.id,
});
},
(error) => {
alert("map error: "+error.message);
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
Android is working fine and getting the correct location but for IOS it's not working Also, it's not asking for allow location persmission. I am getting below error:
PERMISSION_DENIED: 1
POSITION_UNAVAILABLE: 2
TIMEOUT: 3
code: 3
message: "Unable to fetch location within 15.0s."
This is my info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>$(PRODUCT_NAME) would like to access your location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>$(PRODUCT_NAME) would like to access your location.</string>
This is background modes from xcode
I have used the react-native-geolocation-service for getting user current location here is my code
App.js:
import Geolocation from 'react-native-geolocation-service';
async componentDidMount() {
if(Platform.OS === 'ios'){
this.getCurrentLocation();
}else{
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Device current location permission',
message:
'Allow app to get your current location',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.getCurrentLocation();
} else {
console.log('Location permission denied');
}
} catch (err) {
console.warn(err);
}
}
}
getCurrentLocation(){
Geolocation.requestAuthorization();
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
console.log("map error: ",error);
console.log(error.code, error.message);
},
{ enableHighAccuracy: false, timeout: 15000, maximumAge: 10000 }
);
}
MapScreen.js
import Geolocation from 'react-native-geolocation-service';
componentDidMount() {
this.updateCurrentPosiiton();
}
updateCurrentPosiiton () {
Geolocation.getCurrentPosition(
(position) => {
let d_lat = position.coords.latitude;
let d_lng = position.coords.longitude;
this.setState({
current_lat: position.coords.latitude,
current_lng: position.coords.longitude
})
// console.log('aayaaa');
this.props.updateGps(d_lat,d_lng);
this.getTrackData(d_lat,d_lng);
},
(error) => {
console.log("map error: ",error);
console.log(error.code, error.message);
},
{ enableHighAccuracy: false, timeout: 15000, maximumAge: 10000 }
);
}
Please let me know if any issue.
I have solved this issue by this
async requestPermission() {
try {
const granted = await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
]).then((result) => {
console.log(result);
if (
result['android.permission.ACCESS_COARSE_LOCATION'] &&
result['android.permission.ACCESS_FINE_LOCATION'] === 'granted'
) {
this.getLocation();
this.setState({
permissionsGranted: true,
});
}
});
} catch (err) {
console.warn(err);
}
}
getLocation() {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
);
}
componentDidMount() {
if (Platform.OS === 'ios') {
Geolocation.requestAuthorization('always').then((res) => {
console.log(res);
});
}
if (Platform.OS === 'android') {
this.requestPermission();
} else {
this.getLocation();
}
}
make sure you called this function with parameter Geolocation.requestAuthorization('always') or Geolocation.requestAuthorization('whenInUse')

React Native library to track user location

Which library will be most suitable for Android and iOS to be able to track user location continuously even if the app is running in background.
I need to track user's location to send notification that the user has entered a specific location and upon exiting the user has left the location.
You can use geolocation like this way:
getUserCurrentLocation = async () => {
return new Promise((resolve, reject) => {
try {
navigator.geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords;
resolve({ lat: latitude, lng: longitude })
}, error => {
console.log(`ERROR(${error.code}): ${error.message}`);
resolve({ error })
} // , { enableHighAccuracy: true, timeout: 10000, maximumAge: 1000 }
);
setTimeout(() => { resolve({ error: { code: 3 } }) }, 5000);
} catch (e) {
resolve({ error: { code: 3 } })
}
})
};