react-native-background-geolocation
react-native-background-geolocation copied to clipboard
[Help Wanted]: Clarification on Background Tracking Behavior While Driving
Required Reading
- [x] Confirmed
Plugin Version
"react-native-background-geolocation": "^4.18.6"
Mobile operating-system(s)
- [x] iOS
- [x] Android
Device Manufacturer(s) and Model(s)
samsung m30
Device operating-systems(s)
android
React Native / Expo version
react native 0.73.4
What do you require assistance about?
I purchased a React Native Background Geolocation license and have one clarification:
Does the background tracking only work based on physical activity (like walking or moving)? For example, if I'm driving a vehicle and the phone is kept in a stable position, will the background tracking still run and collect location data?
[Optional] Plugin Code and/or Config
import BackgroundGeolocation from 'react-native-background-geolocation';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createLiveTracking } from './services/hsa.service';
import { Alert } from 'react-native';
import { startBackgroundTask } from './FlightModeAndLocation'
let lastUpdateTimestamp = 0;
export async function requestLocationPermission() {
try {
const state = await BackgroundGeolocation.requestPermission();
return state === BackgroundGeolocation.AUTHORIZATION_STATUS_ALWAYS ||
state === BackgroundGeolocation.AUTHORIZATION_STATUS_WHEN_IN_USE;
} catch (error) {
console.error('Error requesting location permission:', error);
return false;
}
}
export async function getCurrentLocation() {
return new Promise((resolve, reject) => {
BackgroundGeolocation.getCurrentPosition(
{
samples: 1,
persist: false,
timeout: 5000,
},
(location) => {
resolve({
lat: location.coords.latitude,
lng: location.coords.longitude,
});
},
(error) => {
console.error('Location error:', error);
if (error === 1) {
console.log('Permission issue: Requesting location access...');
requestLocationPermission();
}
reject(false);
}
);
});
}
export async function startLocationTracing(payload) {
try {
const userId = await AsyncStorage.getItem('userId');
if (!userId) {
console.warn('User ID not found in storage.');
return;
}
BackgroundGeolocation.ready({
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 0,
locationUpdateInterval: 10000,
fastestLocationUpdateInterval: 10000,
stopOnTerminate: false,
startOnBoot: true,
foregroundService: true,
enableHeadless: true,
heartbeatInterval: 10,
allowIdenticalLocations: true,
preventSuspend: true,
locationAuthorizationRequest: 'Always',
debug: false,
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
}).then((state) => {
if (!state.enabled) {
BackgroundGeolocation.start().then(() => {
console.log("- Start success");
Alert.alert("Success", "BackgroundGeolocation started successfully!");
}).catch((error) => {
console.error("- Start failed: ", error);
});
}
});
const handleLocationUpdate = async (eventType) => {
const now = Date.now();
if (now - lastUpdateTimestamp >= 10000) { // 10 seconds
lastUpdateTimestamp = now;
const location = await BackgroundGeolocation.getCurrentPosition({
samples: 1,
persist: false,
});
const data = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
user: userId,
dateTime: location.timestamp,
...payload,
};
// console.log(`[${eventType}] Sending location data to server:`, data);
await createLiveTracking(data);
await AsyncStorage.setItem('locationPayload', JSON.stringify(payload));
startBackgroundTask(payload);
} else {
// console.log(`[${eventType}] Skipped - Throttled`);
}
};
BackgroundGeolocation.onHeartbeat(() => handleLocationUpdate('onHeartbeat'));
BackgroundGeolocation.onMotionChange(() => handleLocationUpdate('onMotionChange'));
BackgroundGeolocation.onLocation(() => handleLocationUpdate('onLocation'));
} catch (error) {
console.error('Error starting location tracing:', error);
}
}
let locationInterval = null;
export function stopLocationTracing() {
if (locationInterval) {
clearInterval(locationInterval);
locationInterval = null;
}
BackgroundGeolocation.stop();
console.log('Location tracking stopped.');
}
[Optional] Relevant log output
Let me clarify that:
if I'm driving a vehicle and the phone is kept in a stable position, will the background tracking still run and collect location data?
Yes.
This issue is stale because it has been open for 30 days with no activity.
This issue was closed because it has been inactive for 14 days since being marked as stale.