• Stars
    star
    187
  • Rank 206,464 (Top 5 %)
  • Language
    Java
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Capacitor plugin that sends you geolocation updates, even while the app is in the background.

Background Geolocation

A Capacitor plugin which lets you receive geolocation updates even while the app is backgrounded. Only iOS and Android platforms are supported.

Usage

import {registerPlugin} from "@capacitor/core";
const BackgroundGeolocation = registerPlugin("BackgroundGeolocation");

// To start listening for changes in the device's location, add a new watcher.
// You do this by calling 'addWatcher' with an options object and a callback. A
// Promise is returned, which resolves to the callback ID used to remove the
// watcher in the future. The callback will be called every time a new location
// is available. Watchers can not be paused, only removed. Multiple watchers may
// exist simultaneously.
BackgroundGeolocation.addWatcher(
    {
        // If the "backgroundMessage" option is defined, the watcher will
        // provide location updates whether the app is in the background or the
        // foreground. If it is not defined, location updates are only
        // guaranteed in the foreground. This is true on both platforms.

        // On Android, a notification must be shown to continue receiving
        // location updates in the background. This option specifies the text of
        // that notification.
        backgroundMessage: "Cancel to prevent battery drain.",

        // The title of the notification mentioned above. Defaults to "Using
        // your location".
        backgroundTitle: "Tracking You.",

        // Whether permissions should be requested from the user automatically,
        // if they are not already granted. Defaults to "true".
        requestPermissions: true,

        // If "true", stale locations may be delivered while the device
        // obtains a GPS fix. You are responsible for checking the "time"
        // property. If "false", locations are guaranteed to be up to date.
        // Defaults to "false".
        stale: false,

        // The minimum number of metres between subsequent locations. Defaults
        // to 0.
        distanceFilter: 50
    },
    function callback(location, error) {
        if (error) {
            if (error.code === "NOT_AUTHORIZED") {
                if (window.confirm(
                    "This app needs your location, " +
                    "but does not have permission.\n\n" +
                    "Open settings now?"
                )) {
                    // It can be useful to direct the user to their device's
                    // settings when location permissions have been denied. The
                    // plugin provides the 'openSettings' method to do exactly
                    // this.
                    BackgroundGeolocation.openSettings();
                }
            }
            return console.error(error);
        }

        return console.log(location);
    }
).then(function after_the_watcher_has_been_added(watcher_id) {
    // When a watcher is no longer needed, it should be removed by calling
    // 'removeWatcher' with an object containing its ID.
    BackgroundGeolocation.removeWatcher({
        id: watcher_id
    });
});

// The location object.
{
    // Longitude in degrees.
    longitude: 131.723423719132,
    // Latitude in degrees.
    latitude: -22.40106297456,
    // Radius of horizontal uncertainty in metres, with 68% confidence.
    accuracy: 11,
    // Metres above sea level (or null).
    altitude: 65,
    // Vertical uncertainty in metres, with 68% confidence (or null).
    altitudeAccuracy: 4,
    // Deviation from true north in degrees (or null).
    bearing: 159.60000610351562,
    // True if the location was simulated by software, rather than GPS.
    simulated: false,
    // Speed in metres per second (or null).
    speed: 23.51068878173828,
    // Time the location was produced, in milliseconds since the unix epoch.
    time: 1562731602000
}

// If you just want the current location, try something like this. The longer
// the timeout, the more accurate the guess will be. I wouldn't go below about
// 100ms.
function guess_location(callback, timeout) {
    let last_location;
    BackgroundGeolocation.addWatcher(
        {
            requestPermissions: false,
            stale: true
        },
        function (location) {
            last_location = location || undefined;
        }
    ).then(function (id) {
        setTimeout(function () {
            callback(last_location);
            Plugins.BackgroundGeolocation.removeWatcher({id});
        }, timeout);
    });
}

Typescript support

import {BackgroundGeolocationPlugin} from "@capacitor-community/background-geolocation";
const BackgroundGeolocation = registerPlugin<BackgroundGeolocationPlugin>("BackgroundGeolocation");

Installation

Different versions of the plugin support different versions of Capacitor:

Capacitor Plugin
v2 v0.3
v3 v1
v4 v1
v5 v1

Read the documentation for v0.3 here.

npm install @capacitor-community/background-geolocation
npx cap update

iOS

Add the following keys to Info.plist.:

<dict>
  ...
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>We need to track your location</string>
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>We need to track your location while your device is locked.</string>
  <key>UIBackgroundModes</key>
  <array>
    <string>location</string>
  </array>
  ...
</dict>

Android

Set the the android.useLegacyBridge option to true in your Capacitor configuration. This prevent location updates from halting after 5 minutes in the background. See https://capacitorjs.com/docs/config and #89.

On Android 13+, the app needs the POST_NOTIFICATIONS runtime permission to show the persistent notification informing the user that their location is being used in the background. You may need to request this permission from the user, see https://developer.android.com/develop/ui/views/notifications/notification-permission.

Configration specific to Android can be made in strings.xml:

<resources>
    <!--
        The channel name for the background notification. This will be visible
        when the user presses & holds the notification. It defaults to
        "Background Tracking".
    -->
    <string name="capacitor_background_geolocation_notification_channel_name">
        Background Tracking
    </string>

    <!--
        The icon to use for the background notification. Note the absence of a
        leading "@". It defaults to "mipmap/ic_launcher", the app's launch icon.

        If a raster image is used to generate the icon (as opposed to a vector
        image), it must have a transparent background. To make sure your image
        is compatible, select "Notification Icons" as the Icon Type when
        creating the image asset in Android Studio.
    -->
    <string name="capacitor_background_geolocation_notification_icon">
        drawable/ic_tracking
    </string>
</resources>

Changelog

v1.2.14

  • Adds support for Capacitor v5.

v1.2.3

  • Adds support for Capacitor v4.

v1.2.2

  • Prevents location updates from halting on iOS due to extended inactivity.

v1.2.1

  • Fixes background location updates for some devices running Android 12.

v1.2.0

  • On iOS, the status bar now turns blue whilst the location is being watched in the background. This provides the user a straightforward way to return to the app.

v1.0.4

  • Adds the ACCESS_COARSE_LOCATION permission. This is required for apps which target Android 12 (API level 31). A preceeding example shows how to add this permission to your app's manifest.

v1.0.0

  • BREAKING: addWatcher now returns a Promise which resolves to the callback ID, rather than the callback ID itself.
  • BREAKING: The plugin is imported via Capacitor's registerPlugin function, rather than from the Plugins object.
  • BREAKING: Drops support for iOS v11 and Capacitor v2.
  • Adds support for Capacitor v3.

More Repositories

1

sqlite

Community plugin for native & electron SQLite databases
Swift
463
star
2

barcode-scanner

A fast and efficient (QR) barcode scanner for Capacitor
Java
435
star
3

electron

Deploy your Capacitor apps to Linux, Mac, and Windows desktops, with the Electron platform! 🖥️
TypeScript
327
star
4

bluetooth-le

Capacitor plugin for Bluetooth Low Energy
TypeScript
277
star
5

react-hooks

⚡️ React hooks for Capacitor ⚡️
TypeScript
244
star
6

fcm

Enable Firebase Cloud Messaging for Capacitor apps
TypeScript
240
star
7

generic-oauth2

Generic Capacitor OAuth 2 client plugin. Stop the war in Ukraine!
Java
232
star
8

admob

Community plugin for using Google AdMob
Java
209
star
9

http

Community plugin for native HTTP
Java
209
star
10

camera-preview

Capacitor plugin that allows camera interaction from HTML code
Java
188
star
11

stripe

Stripe Mobile SDK wrapper for Capacitor
Java
188
star
12

google-maps

Capacitor Plugin using native Google Maps SDK for Android and iOS.
Java
152
star
13

in-app-review

Let users rate your app using native review app dialog for both Android and iOS.
TypeScript
144
star
14

apple-sign-in

Sign in with Apple Support
Swift
137
star
15

vue-cli-plugin-capacitor

A Vue CLI 3/4 Plugin for Capacitor
JavaScript
131
star
16

keep-awake

⚡️ Capacitor plugin to prevent devices from dimming or locking the screen.
Java
125
star
17

firebase-analytics

Enable Firebase Analytics for Capacitor Apps
Java
122
star
18

contacts

Contacts Plugin for Capacitor
Java
114
star
19

tauri

Deploy your Capacitor apps to Linux, Mac, and Windows desktops, with the Tauri platform! 🖥️
TypeScript
108
star
20

native-audio

Java
104
star
21

facebook-login

Facebook Login support
Java
101
star
22

media

Capacitor plugin for saving and retrieving photos and videos, and managing photo albums.
TypeScript
100
star
23

text-to-speech

⚡️ Capacitor plugin for synthesizing speech from text.
Java
93
star
24

speech-recognition

Java
84
star
25

date-picker

Native DateTime Picker Plugin for Capacitor Apps
Swift
84
star
26

privacy-screen

⚡️ Capacitor plugin that protects your app from displaying a screenshot in Recents screen/App Switcher.
Swift
77
star
27

proposals

Plugin and platform requests ✋
74
star
28

app-icon

Capacitor plugin to programmatically change the app icon.
Java
74
star
29

firebase-crashlytics

⚡️ Capacitor plugin for Firebase Crashlytics.
Java
70
star
30

file-opener

Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri. This plugin is similar to cordova-plugin-file-opener2 without installation support.
Swift
64
star
31

intercom

Enable Intercom for Capacitor apps
TypeScript
57
star
32

photoviewer

PhotoViewer table images with fullscreen and sharing capabilities
Swift
49
star
33

examples

Examples of using Capacitor with popular web frameworks and libraries
JavaScript
46
star
34

safe-area

Capacitor Plugin that exposes the safe area insets from the native iOS/Android device to your web project.
Kotlin
46
star
35

welcome

Introduction to the Capacitor Community org 👋
37
star
36

appcenter-sdk-capacitor

Capacitor Plugin for Microsoft's Visual Studio App Center SDK.
TypeScript
35
star
37

in-app-purchases

WIP: In App Purchases plugin for Capacitor
Java
27
star
38

native-market

Java
26
star
39

realm

Java
25
star
40

firebase-remote-config

TypeScript
23
star
41

screen-brightness

Java
23
star
42

.github

Template repo for new community plugins
17
star
43

twitter

Capacitor plugin to enable TwitterKit
TypeScript
11
star
44

card-scanner

Simple card scanner for Capacitor Applications.
Swift
11
star
45

flipper

Java
10
star
46

auth0

TypeScript
9
star
47

volume-buttons

Capacitor Volume Buttons. The plugin enables to listen to hardware volume button presses. This plugin is based on https://github.com/thiagobrez/capacitor-volume-buttons
Swift
7
star
48

google-maps-examples

Vue
5
star
49

uxcam

UXCam and FullStory app analytics
Java
5
star
50

advertising-id

Allows access to the IDFA (iOS) and AAID (Android)
Swift
5
star
51

android-security-provider

Capacitor plugin with method to check and update the Android Security Provider.
Java
3
star
52

tap-jacking

Capacitor plugin to prevent tap jacking on Android devices
Java
2
star
53

mdm-appconfig

Capacitor community plugin for reading app configurations written by a MDM (see appconfig.org) such as VMWare Workspace One.
Java
2
star
54

exif

This plugin offers utility functions for interacting with image exif metadata
Swift
2
star
55

play-integrity

A Capacitor plugin to use the Play Integrity API
Java
1
star
56

device-check

A Capacitor plugin to use Apple's DeviceCheck API
Java
1
star