Skip to main content

Types & Interfaces

All TypeScript types and interfaces exported by the library, grouped by category.

import type {
Coords,
TrackingStatus,
TrackingOptions,
LocationUpdateEvent,
LocationWarningEvent,
LocationWarningType,
NotificationAction,
NotificationActionEvent,
NotificationOptions,
GeofenceRegion,
GeofenceTransitionEvent,
LocationPermissionState,
NotificationPermissionState,
PermissionState,
PermissionRationale,
RequestPermissionsOptions,
UseLocationPermissionsResult,
UseBackgroundLocationResult,
UseLocationTrackingOptions,
UseLocationTrackingResult,
UseLocationUpdatesOptions,
UseLocationUpdatesResult,
UseGeofencingOptions,
UseGeofencingReturn,
UseGeofenceEventsOptions,
} from '@gabriel-sisjr/react-native-background-location';

Tracking Types

Coords

Location coordinates with extended location data. Returned by getLocations() and provided in location update events.

interface Coords {
/** Latitude in decimal degrees */
latitude: string;
/** Longitude in decimal degrees */
longitude: string;
/** Timestamp in milliseconds since Unix epoch */
timestamp: number;
/** Horizontal accuracy in meters */
accuracy?: number;
/** Altitude in meters above sea level */
altitude?: number;
/** Speed in meters per second */
speed?: number;
/** Bearing in degrees (0-360) */
bearing?: number;
/** Vertical accuracy in meters (Android API 26+) */
verticalAccuracyMeters?: number;
/** Speed accuracy in meters per second (Android API 26+) */
speedAccuracyMetersPerSecond?: number;
/** Bearing accuracy in degrees (Android API 26+) */
bearingAccuracyDegrees?: number;
/** Elapsed realtime in nanoseconds since system boot */
elapsedRealtimeNanos?: number;
/** Location provider (gps, network, passive, etc.) */
provider?: string;
/** Whether the location is from a mock provider (Android API 18+) */
isFromMockProvider?: boolean;
}
PropertyTypeRequiredPlatformDescription
latitudestringYesBothLatitude in decimal degrees
longitudestringYesBothLongitude in decimal degrees
timestampnumberYesBothMilliseconds since Unix epoch
accuracynumberNoBothHorizontal accuracy in meters
altitudenumberNoBothAltitude in meters above sea level
speednumberNoBothSpeed in meters per second
bearingnumberNoBothBearing in degrees (0-360)
verticalAccuracyMetersnumberNoAndroid 26+Vertical accuracy in meters
speedAccuracyMetersPerSecondnumberNoAndroid 26+Speed accuracy in m/s
bearingAccuracyDegreesnumberNoAndroid 26+Bearing accuracy in degrees
elapsedRealtimeNanosnumberNoBothNanoseconds since system boot
providerstringNoBothLocation provider name
isFromMockProviderbooleanNoAndroid 18+Whether from a mock provider

TrackingStatus

Describes the current tracking state. Returned by isTracking().

interface TrackingStatus {
active: boolean;
tripId?: string;
}
PropertyTypeRequiredDescription
activebooleanYesWhether tracking is currently running
tripIdstringNoCurrent trip identifier (present when active is true)

LocationUpdateEvent

Location update event with extended location data. Emitted by the native event emitter.

interface LocationUpdateEvent {
tripId: string;
latitude: string;
longitude: string;
timestamp: number;
accuracy?: number;
altitude?: number;
speed?: number;
bearing?: number;
verticalAccuracyMeters?: number;
speedAccuracyMetersPerSecond?: number;
bearingAccuracyDegrees?: number;
elapsedRealtimeNanos?: number;
provider?: string;
isFromMockProvider?: boolean;
}

Same fields as Coords plus a required tripId field.

PropertyTypeRequiredDescription
tripIdstringYesTrip identifier for this location update

All other fields match the Coords interface.


LocationWarningType

Union type for warning categories emitted by the location service.

type LocationWarningType =
| 'SERVICE_TIMEOUT'
| 'TASK_REMOVED'
| 'LOCATION_UNAVAILABLE';
ValueDescription
'SERVICE_TIMEOUT'Android 15+ foreground service timeout reached; service is restarting
'TASK_REMOVED'App was swiped from recents; tracking continues in background
'LOCATION_UNAVAILABLE'GPS signal lost or location services disabled

LocationWarningEvent

Warning event emitted by the location service for non-critical issues that do not stop tracking.

interface LocationWarningEvent {
/** Trip identifier for this warning */
tripId: string;
/** Type of warning */
type: LocationWarningType;
/** Human-readable description of the warning */
message: string;
/** Timestamp when the warning was emitted */
timestamp: number;
}
PropertyTypeRequiredDescription
tripIdstringYesTrip identifier for this warning
typeLocationWarningTypeYesWarning category
messagestringYesHuman-readable description
timestampnumberYesTimestamp when emitted

NotificationAction

Configuration for a notification action button. Up to 3 actions can be added to the foreground service notification.

interface NotificationAction {
/** Unique identifier for this action */
id: string;
/** Label displayed on the action button */
label: string;
}
PropertyTypeRequiredDescription
idstringYesUnique identifier used to identify which action was pressed
labelstringYesLabel displayed on the action button

NotificationActionEvent

Event emitted when a notification action button is pressed.

interface NotificationActionEvent {
/** Trip identifier for the active tracking session */
tripId: string;
/** ID of the action that was pressed */
actionId: string;
}
PropertyTypeRequiredDescription
tripIdstringYesTrip identifier for the active tracking session
actionIdstringYesID of the action that was pressed (matches NotificationAction.id)

TrackingOptions

Configuration options for location tracking. Passed to startTracking().

interface TrackingOptions {
updateInterval?: number;
fastestInterval?: number;
maxWaitTime?: number;
accuracy?: LocationAccuracy;
activityType?: LocationActivityType;
waitForAccurateLocation?: boolean;
distanceFilter?: number;
notificationOptions?: NotificationOptions;
foregroundOnly?: boolean;
onUpdateInterval?: number;
}
PropertyTypeDefaultPlatformDescription
updateIntervalnumber5000AndroidInterval between location updates in milliseconds
fastestIntervalnumber3000AndroidFastest interval between updates in milliseconds. The system never updates faster than this.
maxWaitTimenumber10000AndroidMaximum wait time in milliseconds before delivering batched updates
accuracyLocationAccuracyHIGH_ACCURACYBothLocation accuracy priority level
activityTypeLocationActivityTypeLocationActivityType.OTHERiOSMaps to CLLocationManager.activityType. Controls how iOS treats the tracking activity (e.g., pausing on inactivity for AUTOMOTIVE_NAVIGATION).
waitForAccurateLocationbooleanfalseAndroidWhether to delay updates until accurate location is available
distanceFilternumber0AndroidMinimum distance in meters between updates. 0 = no filter.
notificationOptionsNotificationOptionsBothForeground service notification configuration
foregroundOnlybooleanfalseAndroidForeground-only mode. Does not require background location permission.
onUpdateIntervalnumberundefinedBothThrottle interval for the onLocationUpdate callback in milliseconds. Locations are still collected at updateInterval rate.

Notification Types

NotificationOptions

Unified notification configuration interface used across the library for foreground service notifications and geofence transition notifications.

For geofencing, the title and text fields support template variables. See GEOFENCE_TEMPLATE_VARS.

interface NotificationOptions {
enabled?: boolean;
title?: string;
text?: string;
channelName?: string;
channelId?: string;
priority?: NotificationPriority;
smallIcon?: string;
largeIcon?: string;
color?: string;
showTimestamp?: boolean;
subtext?: string;
actions?: NotificationAction[];
transitionOverrides?: Partial<
Record<
'ENTER' | 'EXIT' | 'DWELL',
Omit<NotificationOptions, 'transitionOverrides' | 'enabled'>
>
>;
}
PropertyTypeDefaultPlatformDescription
enabledbooleantrueBothWhether notifications are shown
titlestringBothNotification title. Supports template variables for geofencing.
textstringBothNotification body text. Supports template variables for geofencing.
channelNamestringAndroidAndroid notification channel name
channelIdstringAndroidAndroid notification channel ID
priorityNotificationPriorityAndroidNotification priority
smallIconstringAndroidAndroid drawable resource name for the small icon
largeIconstringAndroidAndroid drawable resource name for the large icon
colorstringAndroidHex color string for notification accent color
showTimestampbooleanAndroidWhether to show timestamp on the notification
subtextstringAndroidSubtext displayed below the notification content
actionsNotificationAction[]AndroidAction buttons (max 3). Currently supported for foreground service notifications only.
transitionOverridesPartial<Record<...>>BothPer-transition notification overrides (ENTER, EXIT, DWELL)

Note: transitionOverrides allows customizing notification content per transition type. Unspecified fields fall through to the parent config. The enabled and transitionOverrides fields are excluded from per-transition overrides to prevent recursion.


GEOFENCE_TEMPLATE_VARS

Constant object providing available template variables for geofence notification title and text fields. Variables are resolved at notification time on the native side.

const GEOFENCE_TEMPLATE_VARS = {
IDENTIFIER: '{{identifier}}',
TRANSITION_TYPE: '{{transitionType}}',
LATITUDE: '{{latitude}}',
LONGITUDE: '{{longitude}}',
RADIUS: '{{radius}}',
TIMESTAMP: '{{timestamp}}',
} as const;
KeyTemplateResolved to
IDENTIFIER{{identifier}}The geofence's identifier string
TRANSITION_TYPE{{transitionType}}ENTER, EXIT, or DWELL
LATITUDE{{latitude}}Device latitude at transition
LONGITUDE{{longitude}}Device longitude at transition
RADIUS{{radius}}Geofence radius in meters
TIMESTAMP{{timestamp}}Transition timestamp

Usage

import { GEOFENCE_TEMPLATE_VARS } from '@gabriel-sisjr/react-native-background-location';

const options = {
title: 'Geofence Alert',
text: `You entered ${GEOFENCE_TEMPLATE_VARS.IDENTIFIER} at ${GEOFENCE_TEMPLATE_VARS.TIMESTAMP}`,
};

Permission Types

LocationPermissionState

Granular status information for location permissions.

interface LocationPermissionState {
hasPermission: boolean;
status: LocationPermissionStatus;
canRequestAgain: boolean;
}
PropertyTypeDescription
hasPermissionbooleantrue if status is GRANTED or WHEN_IN_USE
statusLocationPermissionStatusCurrent permission status enum value
canRequestAgainbooleanWhether the permission dialog can be shown again

NotificationPermissionState

Granular status information for notification permissions.

interface NotificationPermissionState {
hasPermission: boolean;
status: NotificationPermissionStatus;
canRequestAgain: boolean;
}
PropertyTypeDescription
hasPermissionbooleantrue if status is GRANTED
statusNotificationPermissionStatusCurrent permission status enum value
canRequestAgainbooleanWhether the permission dialog can be shown again

PermissionState

Combined permission state for both location and notification permissions.

interface PermissionState {
hasAllPermissions: boolean;
location: LocationPermissionState;
notification: NotificationPermissionState;
}
PropertyTypeDescription
hasAllPermissionsbooleantrue only when both location and notification are granted
locationLocationPermissionStateLocation permission details
notificationNotificationPermissionStateNotification permission details

PermissionRationale

Localized strings shown in an Android system permission dialog (PermissionsAndroid.request). Reusable for any of the dialogs the library may surface (background-location today; foreground-location and notification reserved for future releases).

Currently only consumed by RequestPermissionsOptions.backgroundRationale on Android API 29+. The shape intentionally carries no platform prefix in its name so future sibling fields can share it.

All fields are optional. Any field that is omitted, undefined, null, an empty string, or whitespace-only falls back to the library's built-in English default for that field. Each field is resolved independently -- passing { title: 'Permissão' } only overrides the title and leaves the message and three button labels at their defaults.

interface PermissionRationale {
title?: string;
message?: string;
buttonPositive?: string;
buttonNegative?: string;
buttonNeutral?: string;
}
PropertyTypeRequiredDefaultDescription
titlestringNoBackground Location PermissionDialog title.
messagestringNoThis app needs access to your location in the background to track your trips.Dialog body explaining why background location is required.
buttonPositivestringNoOKPositive (accept) button label.
buttonNegativestringNoCancelNegative (deny) button label.
buttonNeutralstringNoAsk Me LaterNeutral ("ask later") button label.

Note: The default English wording is internal and may evolve between minor versions without a SemVer bump. Pass an explicit PermissionRationale if you need stable copy for QA, screenshots, or store review.

Example

import type { PermissionRationale } from '@gabriel-sisjr/react-native-background-location';

const ptBR: PermissionRationale = {
title: 'Permissão de localização',
message:
'Precisamos da sua localização em segundo plano para registrar suas viagens.',
buttonPositive: 'Permitir',
buttonNegative: 'Cancelar',
buttonNeutral: 'Mais tarde',
};

RequestPermissionsOptions

Options accepted by useLocationPermissions().requestPermissions(...).

The flat-envelope shape is intentional: future siblings -- currently planned foregroundRationale (for PermissionsAndroid.requestMultiple) and notificationRationale (for POST_NOTIFICATIONS) -- can be added as additional optional fields without a breaking rename. Each field is named after its target dialog so the call site is self-documenting.

interface RequestPermissionsOptions {
backgroundRationale?: PermissionRationale;
}
PropertyTypePlatformDescription
backgroundRationalePermissionRationaleAndroid API 29+Optional localized copy for the Android background-location rationale dialog (PermissionsAndroid.request(ACCESS_BACKGROUND_LOCATION, ...)). Silently ignored on iOS, on Android < 29, on the foreground-only flow (requestMultiple), and on the notification permission request.

Note: Future releases may add foregroundRationale and notificationRationale as sibling optional fields. They are reserved and not yet implemented.

Example

import { useLocationPermissions } from '@gabriel-sisjr/react-native-background-location';

const { requestPermissions } = useLocationPermissions();

// Example in Brazilian Portuguese (PT-BR)
const options: PermissionRationale = {
backgroundRationale: {
title: 'Permissão de localização',
message:
'Precisamos da sua localização em segundo plano para registrar suas viagens.',
},
};

await requestPermissions(options);

UseLocationPermissionsResult

Return type for the useLocationPermissions hook.

interface UseLocationPermissionsResult {
permissionStatus: PermissionState;
requestPermissions: (options?: RequestPermissionsOptions) => Promise<boolean>;
checkPermissions: () => Promise<boolean>;
isRequesting: boolean;
}
PropertyTypeDescription
permissionStatusPermissionStateCurrent permission state
requestPermissions(options?: RequestPermissionsOptions) => Promise<boolean>Request all permissions. Returns true if location is granted. Accepts an optional RequestPermissionsOptions argument.
checkPermissions() => Promise<boolean>Check permissions without requesting. Returns true if location is granted.
isRequestingbooleanWhether a permission request is in progress

Geofencing Types

GeofenceRegion

Defines a circular geofence region for monitoring.

interface GeofenceRegion {
identifier: string;
latitude: number;
longitude: number;
radius: number;
transitionTypes?: GeofenceTransitionType[];
loiteringDelay?: number;
expirationDuration?: number;
metadata?: Record<string, unknown>;
notificationOptions?: NotificationOptions | false;
}
PropertyTypeDefaultDescription
identifierstringUnique identifier for this geofence (required)
latitudenumberCenter latitude (-90 to 90)
longitudenumberCenter longitude (-180 to 180)
radiusnumberRadius in meters (minimum 100)
transitionTypesGeofenceTransitionType[][ENTER, EXIT]Transition types to monitor
loiteringDelaynumber30000Loitering delay in milliseconds for DWELL detection
expirationDurationnumberundefinedExpiration duration in milliseconds. If omitted, remains active indefinitely.
metadataRecord<string, unknown>undefinedOptional JSON-serializable metadata
notificationOptionsNotificationOptions | falseundefinedPer-geofence notification config. Set to false to suppress notifications for this geofence.

Note: The notificationOptions resolution chain (highest to lowest priority):

  1. Per-geofence notificationOptions (this field)
  2. Global config via configureGeofenceNotifications()
  3. Platform defaults

GeofenceTransitionEvent

Event emitted when a geofence transition is detected.

interface GeofenceTransitionEvent {
geofenceId: string;
transitionType: GeofenceTransitionType;
latitude: number;
longitude: number;
timestamp: string;
distanceFromCenter: number;
metadata?: Record<string, unknown>;
}
PropertyTypeDescription
geofenceIdstringIdentifier of the geofence that triggered the event
transitionTypeGeofenceTransitionTypeType of transition detected (ENTER, EXIT, or DWELL)
latitudenumberDevice latitude at the moment of transition
longitudenumberDevice longitude at the moment of transition
timestampstringTimestamp of the transition (ISO 8601 string)
distanceFromCenternumberDistance from the center of the geofence in meters
metadataRecord<string, unknown>Metadata associated with the geofence, if any

Hook Types

UseBackgroundLocationResult

Return type for the useBackgroundLocation hook.

interface UseBackgroundLocationResult {
tripId: string | null;
isTracking: boolean;
locations: Coords[];
isLoading: boolean;
error: Error | null;
startTracking: (
customTripId?: string,
options?: TrackingOptions
) => Promise<string | null>;
stopTracking: () => Promise<void>;
refreshLocations: () => Promise<void>;
clearCurrentTrip: () => Promise<void>;
clearError: () => void;
}
PropertyTypeDescription
tripIdstring | nullCurrent trip ID, or null if not tracking
isTrackingbooleanWhether tracking is active
locationsCoords[]All locations collected for the current trip
isLoadingbooleanWhether an async operation is in progress
errorError | nullLast error that occurred
startTracking(customTripId?, options?) => Promise<string | null>Start tracking with optional trip ID and options
stopTracking() => Promise<void>Stop tracking
refreshLocations() => Promise<void>Reload locations from database
clearCurrentTrip() => Promise<void>Clear all data for the current trip
clearError() => voidReset error state to null

UseLocationTrackingOptions

Options for the useBackgroundLocation hook.

interface UseLocationTrackingOptions {
autoStart?: boolean;
tripId?: string;
options?: TrackingOptions;
onTrackingStart?: (tripId: string) => void;
onTrackingStop?: () => void;
onError?: (error: Error) => void;
}
PropertyTypeDefaultDescription
autoStartbooleanfalseAutomatically start tracking when component mounts
tripIdstringCustom trip ID to use
optionsTrackingOptionsTracking configuration options
onTrackingStart(tripId: string) => voidCallback when tracking starts
onTrackingStop() => voidCallback when tracking stops
onError(error: Error) => voidCallback when an error occurs

UseLocationTrackingResult

Return type for the useLocationTracking hook.

interface UseLocationTrackingResult {
isTracking: boolean;
tripId: string | null;
refresh: () => Promise<void>;
isLoading: boolean;
}
PropertyTypeDescription
isTrackingbooleanWhether tracking is active
tripIdstring | nullCurrent trip ID, or null
refresh() => Promise<void>Manually re-check tracking status
isLoadingbooleanWhether status is being checked

UseLocationUpdatesOptions

Options for the useLocationUpdates hook.

interface UseLocationUpdatesOptions {
tripId?: string;
onLocationUpdate?: (location: Coords) => void;
onUpdateInterval?: number;
onLocationWarning?: (warning: LocationWarningEvent) => void;
onNotificationAction?: (event: NotificationActionEvent) => void;
autoLoad?: boolean;
}
PropertyTypeDefaultDescription
tripIdstringSpecific trip ID to watch. If not provided, watches all trips.
onLocationUpdate(location: Coords) => voidCallback for each new location
onUpdateIntervalnumberundefinedThrottle interval in milliseconds for the onLocationUpdate callback
onLocationWarning(warning: LocationWarningEvent) => voidCallback for service warnings
onNotificationAction(event: NotificationActionEvent) => voidCallback for notification action button presses
autoLoadbooleantrueWhether to automatically load existing locations on mount

UseLocationUpdatesResult

Return type for the useLocationUpdates hook.

interface UseLocationUpdatesResult {
tripId: string | null;
isTracking: boolean;
locations: Coords[];
lastLocation: Coords | null;
lastWarning: LocationWarningEvent | null;
isLoading: boolean;
error: Error | null;
clearError: () => void;
clearLocations: () => Promise<void>;
refreshLocations: () => Promise<void>;
}
PropertyTypeDescription
tripIdstring | nullCurrent trip ID being watched
isTrackingbooleanWhether tracking is active
locationsCoords[]All locations received, updated in real time
lastLocationCoords | nullMost recently received location
lastWarningLocationWarningEvent | nullMost recent service warning
isLoadingbooleanWhether data is being loaded
errorError | nullLast error that occurred
clearError() => voidReset error state
clearLocations() => Promise<void>Clear all locations for the current trip
refreshLocations() => Promise<void>Manually re-load locations from the database

UseGeofencingOptions

Options for the useGeofencing hook.

interface UseGeofencingOptions {
autoLoad?: boolean;
notificationOptions?: NotificationOptions;
}
PropertyTypeDefaultDescription
autoLoadbooleantrueWhether to automatically load geofences on mount
notificationOptionsNotificationOptionsGlobal notification config. When provided, calls configureGeofenceNotifications() on mount.

UseGeofencingReturn

Return type for the useGeofencing hook.

interface UseGeofencingReturn {
geofences: GeofenceRegion[];
isLoading: boolean;
error: Error | null;
addGeofence: (region: GeofenceRegion) => Promise<void>;
addGeofences: (regions: GeofenceRegion[]) => Promise<void>;
removeGeofence: (identifier: string) => Promise<void>;
removeGeofences: (identifiers: string[]) => Promise<void>;
removeAllGeofences: () => Promise<void>;
maxGeofences: number | null;
refresh: () => Promise<void>;
clearError: () => void;
}
PropertyTypeDescription
geofencesGeofenceRegion[]Currently active geofence regions
isLoadingbooleanWhether an async operation is in progress
errorError | nullLast error that occurred
addGeofence(region) => Promise<void>Register a single geofence
addGeofences(regions) => Promise<void>Register multiple geofences atomically
removeGeofence(identifier) => Promise<void>Remove a single geofence
removeGeofences(identifiers) => Promise<void>Remove multiple geofences
removeAllGeofences() => Promise<void>Remove all geofences
maxGeofencesnumber | nullPlatform limit, or null if not yet loaded
refresh() => Promise<void>Reload geofences and platform limit
clearError() => voidReset error state

UseGeofenceEventsOptions

Options for the useGeofenceEvents hook.

interface UseGeofenceEventsOptions {
onTransition?: (event: GeofenceTransitionEvent) => void;
filter?: GeofenceTransitionType[];
geofenceId?: string;
}
PropertyTypeDefaultDescription
onTransition(event: GeofenceTransitionEvent) => voidCallback when a geofence transition is detected (after filters are applied)
filterGeofenceTransitionType[]Only emit events matching these transition types. If omitted, all transitions fire.
geofenceIdstringOnly emit events for this specific geofence identifier. If omitted, all geofences fire.