Background Geolocation
Capacitor plugin which lets you receive geolocation updates even while the app is backgrounded.
Tested with Capacitor v2. iOS and Android platforms only.
Usage
import {Plugins} from "@capacitor/core";
const {BackgroundGeolocation, Modals} = Plugins;
const id = BackgroundGeolocation.addWatcher(
{
backgroundMessage: "Cancel to prevent battery drain.",
backgroundTitle: "Tracking You.",
requestPermissions: true,
stale: false
},
function callback(location, error) {
if (error) {
if (error.code === "NOT_AUTHORIZED") {
Modals.confirm({
title: "Location Required",
message: (
"This app needs your location, " +
"but does not have permission.\n\n" +
"Open settings now?"
)
}).then(function ({value}) {
if (value) {
BackgroundGeolocation.openSettings();
}
});
}
return console.error(error);
}
return console.log(location);
}
);
BackgroundGeolocation.removeWatcher({id});
{
longitude: 131.723423719132,
latitude: -22.40106297456,
accuracy: 11,
altitude: 65,
altitudeAccuracy: 4,
bearing: 159.60000610351562,
speed: 23.51068878173828,
time: 1562731602000
}
function guess_location(callback, timeout) {
let last_location;
let id = Plugins.BackgroundGeolocation.addWatcher(
{
requestPermissions: false,
stale: true
},
function (location) {
last_location = location || undefined;
}
);
setTimeout(function () {
callback(last_location);
Plugins.BackgroundGeolocation.removeWatcher({id});
}, timeout);
}
Installation
npm install @capacitor-community/background-geolocation
npx cap update
iOS
Specify the following keys in 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>
...
</dict>
Android
Import the plugin in MainActivity.java
:
import com.equimaps.capacitor_background_geolocation.BackgroundGeolocation;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
add(BackgroundGeolocation.class);
}});
}
}
Configure AndroidManifest.xml
:
<manifest>
<application>
<service
android:name="com.equimaps.capacitor_background_geolocation.BackgroundGeolocationService"
android:enabled="true"
android:exported="true"
android:foregroundServiceType="location" />
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-feature android:name="android.hardware.location.gps" />
</manifest>