Gathering detailed insights and metrics for react-native-background-geolocation
Gathering detailed insights and metrics for react-native-background-geolocation
Gathering detailed insights and metrics for react-native-background-geolocation
Gathering detailed insights and metrics for react-native-background-geolocation
react-native-background-geolocation-firebase
Firebase Adapter for react-native-background-geolocation
@connected-home/react-native-geolocation
Basic geolocation + geofencing. Delegates to react-native-background-geolocation for iOS.
@barryhieu/react-native-background-geolocation
Optimized background location tracking
react-native-background-fetch
iOS & Android BackgroundFetch API implementation for React Native
npm install react-native-background-geolocation
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,660 Stars
884 Commits
425 Forks
61 Watching
5 Branches
35 Contributors
Updated on 25 Nov 2024
Minified
Minified + Gzipped
Objective-C (53.44%)
JavaScript (16.55%)
Java (15.09%)
C++ (12.11%)
TypeScript (1.73%)
Shell (0.71%)
Ruby (0.34%)
HTML (0.04%)
Cumulative downloads
Total Downloads
Last day
-1.6%
2,660
Compared to previous day
Last week
-2.6%
12,914
Compared to previous week
Last month
4.4%
58,903
Compared to previous month
Last year
51.1%
653,628
Compared to previous year
Now with Expo support |
---|
The most sophisticated background location-tracking & geofencing module with battery-conscious motion-detection intelligence for iOS and Android.
The plugin's Philosophy of Operation is to use motion-detection APIs (using accelerometer, gyroscope and magnetometer) to detect when the device is moving and stationary.
When the device is detected to be moving, the plugin will automatically start recording a location according to the configured distanceFilter
(meters).
When the device is detected be stationary, the plugin will automatically turn off location-services to conserve energy.
Also available for Flutter, Cordova, NativeScript and pure native apps.
[!NOTE] The Android module requires purchasing a license. However, it will work for DEBUG builds. It will not work with RELEASE builds without purchasing a license. This plugin is supported full-time and field-tested daily since 2013.
1npx expo install react-native-background-geolocation
yarn
1yarn add react-native-background-geolocation
npm
$ npm install react-native-background-geolocation --save
Login to Customer Dashboard to generate an application key: www.transistorsoft.com/shop/customers
Add your license-key to android/app/src/main/AndroidManifest.xml
:
1<manifest xmlns:android="http://schemas.android.com/apk/res/android" 2 package="com.transistorsoft.backgroundgeolocation.react"> 3 4 <application 5 android:name=".MainApplication" 6 android:allowBackup="true" 7 android:label="@string/app_name" 8 android:icon="@mipmap/ic_launcher" 9 android:theme="@style/AppTheme"> 10 11 <!-- react-native-background-geolocation licence --> 12+ <meta-data android:name="com.transistorsoft.locationmanager.license" android:value="YOUR_LICENCE_KEY_HERE" /> 13 . 14 . 15 . 16 </application> 17</manifest>
1import BackgroundGeolocation from "react-native-background-geolocation";
For those using Typescript (recommended), you can also import
the interfaces:
1import BackgroundGeolocation, { 2 State, 3 Config, 4 Location, 5 LocationError, 6 Geofence, 7 GeofenceEvent, 8 GeofencesChangeEvent, 9 HeartbeatEvent, 10 HttpEvent, 11 MotionActivityEvent, 12 MotionChangeEvent, 13 ProviderChangeEvent, 14 ConnectivityChangeEvent 15} from "react-native-background-geolocation"; 16
For more information, see this blog post
There are three main steps to using BackgroundGeolocation
.ready(config)
the plugin..start()
the plugin.[!WARNING] Do not execute any API method which will require accessing location-services until the
.ready(config)
method resolves (Read its API docs), For example:
.getCurrentPosition
.watchPosition
.start
1// NO! .ready() has not resolved. 2BackgroundGeolocation.getCurrentPosition(options); 3BackgroundGeolocation.start(); 4 5BackgroundGeolocation.ready(config).then((state) => { 6 // YES -- .ready() has now resolved. 7 BackgroundGeolocation.getCurrentPosition(options); 8 BackgroundGeolocation.start(); 9}); 10 11// NO! .ready() has not resolved. 12BackgroundGeolocation.getCurrentPosition(options); 13BackgroundGeolocation.start();
1 2import React from 'react'; 3import { 4 Switch, 5 Text, 6 View, 7} from 'react-native'; 8 9import BackgroundGeolocation, { 10 Location, 11 Subscription 12} from "react-native-background-geolocation"; 13 14const HelloWorld = () => { 15 const [enabled, setEnabled] = React.useState(false); 16 const [location, setLocation] = React.useState(''); 17 18 React.useEffect(() => { 19 /// 1. Subscribe to events. 20 const onLocation:Subscription = BackgroundGeolocation.onLocation((location) => { 21 console.log('[onLocation]', location); 22 setLocation(JSON.stringify(location, null, 2)); 23 }) 24 25 const onMotionChange:Subscription = BackgroundGeolocation.onMotionChange((event) => { 26 console.log('[onMotionChange]', event); 27 }); 28 29 const onActivityChange:Subscription = BackgroundGeolocation.onActivityChange((event) => { 30 console.log('[onActivityChange]', event); 31 }) 32 33 const onProviderChange:Subscription = BackgroundGeolocation.onProviderChange((event) => { 34 console.log('[onProviderChange]', event); 35 }) 36 37 /// 2. ready the plugin. 38 BackgroundGeolocation.ready({ 39 // Geolocation Config 40 desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 41 distanceFilter: 10, 42 // Activity Recognition 43 stopTimeout: 5, 44 // Application config 45 debug: true, // <-- enable this hear sounds for background-geolocation life-cycle. 46 logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, 47 stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app. 48 startOnBoot: true, // <-- Auto start tracking when device is powered-up. 49 // HTTP / SQLite config 50 url: 'http://yourserver.com/locations', 51 batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request. 52 autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives. 53 headers: { // <-- Optional HTTP headers 54 "X-FOO": "bar" 55 }, 56 params: { // <-- Optional HTTP params 57 "auth_token": "maybe_your_server_authenticates_via_token_YES?" 58 } 59 }).then((state) => { 60 setEnabled(state.enabled) 61 console.log("- BackgroundGeolocation is configured and ready: ", state.enabled); 62 }); 63 64 return () => { 65 // Remove BackgroundGeolocation event-subscribers when the View is removed or refreshed 66 // during development live-reload. Without this, event-listeners will accumulate with 67 // each refresh during live-reload. 68 onLocation.remove(); 69 onMotionChange.remove(); 70 onActivityChange.remove(); 71 onProviderChange.remove(); 72 } 73 }, []); 74 75 /// 3. start / stop BackgroundGeolocation 76 React.useEffect(() => { 77 if (enabled) { 78 BackgroundGeolocation.start(); 79 } else { 80 BackgroundGeolocation.stop(); 81 setLocation(''); 82 } 83 }, [enabled]); 84 85 return ( 86 <View style={{alignItems:'center'}}> 87 <Text>Click to enable BackgroundGeolocation</Text> 88 <Switch value={enabled} onValueChange={setEnabled} /> 89 <Text style={{fontFamily:'monospace', fontSize:12}}>{location}</Text> 90 </View> 91 ) 92} 93 94export default HelloWorld;
1import React from 'react'; 2import { 3 Switch, 4 Text, 5 View, 6} from 'react-native'; 7 8import BackgroundGeolocation, { 9 Location, 10 Subscription 11} from "react-native-background-geolocation"; 12 13export default class HelloWorld extends React.Component { 14 subscriptions:Subscription[] = []; 15 state:any = {}; 16 constructor(props:any) { 17 super(props); 18 this.state = { 19 enabled: false, 20 location: '' 21 } 22 } 23 24 componentDidMount() { 25 /// 1. Subscribe to BackgroundGeolocation events. 26 this.subscriptions.push(BackgroundGeolocation.onLocation((location) => { 27 console.log('[onLocation]', location); 28 this.setState({location: JSON.stringify(location, null, 2)}) 29 }, (error) => { 30 console.log('[onLocation] ERROR:', error); 31 })) 32 33 this.subscriptions.push(BackgroundGeolocation.onMotionChange((event) => { 34 console.log('[onMotionChange]', event); 35 })) 36 37 this.subscriptions.push(BackgroundGeolocation.onActivityChange((event) => { 38 console.log('[onActivityChange]', event); 39 })) 40 41 this.subscriptions.push(BackgroundGeolocation.onProviderChange((event) => { 42 console.log('[onProviderChange]', event); 43 })) 44 45 /// 2. ready the plugin. 46 BackgroundGeolocation.ready({ 47 // Geolocation Config 48 desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 49 distanceFilter: 10, 50 // Activity Recognition 51 stopTimeout: 5, 52 // Application config 53 debug: true, // <-- enable this hear sounds for background-geolocation life-cycle. 54 logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, 55 stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app. 56 startOnBoot: true, // <-- Auto start tracking when device is powered-up. 57 // HTTP / SQLite config 58 url: 'http://yourserver.com/locations', 59 batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request. 60 autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives. 61 headers: { // <-- Optional HTTP headers 62 "X-FOO": "bar" 63 }, 64 params: { // <-- Optional HTTP params 65 "auth_token": "maybe_your_server_authenticates_via_token_YES?" 66 } 67 }).then((state) => { 68 this.setState({enabled: state.enabled}); 69 console.log("- BackgroundGeolocation is configured and ready: ", state.enabled); 70 }) 71 } 72 73 /// When view is destroyed (or refreshed during development live-reload), 74 /// remove BackgroundGeolocation event subscriptions. 75 componentWillUnmount() { 76 this.subscriptions.forEach((subscription) => subscription.remove()); 77 } 78 79 onToggleEnabled(value:boolean) { 80 console.log('[onToggleEnabled]', value); 81 this.setState({enabled: value}) 82 if (value) { 83 BackgroundGeolocation.start(); 84 } else { 85 this.setState({location: ''}); 86 BackgroundGeolocation.stop(); 87 } 88 } 89 90 render() { 91 return ( 92 <View style={{alignItems:'center'}}> 93 <Text>Click to enable BackgroundGeolocation</Text> 94 <Switch value={this.state.enabled} onValueChange={this.onToggleEnabled.bind(this)} /> 95 <Text style={{fontFamily:'monospace', fontSize:12}}>{this.state.location}</Text> 96 </View> 97 ) 98 } 99}
The BackgroundGeolocation
Javascript API supports Promises for nearly every method (the exceptions are #watchPosition
and adding event-listeners via #onXXX
method (eg: onLocation
). For more information, see the API Documentation
1BackgroundGeolocation.ready({ 2 desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 3 distanceFilter: 50 4}).then(state => { 5 console.log('- BackgroundGeolocation is ready: ', state); 6}).catch(error => { 7 console.warn('- BackgroundGeolocation error: ', error); 8}); 9 10// Or use await in an async function 11try { 12 const state = await BackgroundGeolocation.ready({ 13 desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 14 distanceFilter: 50 15 }) 16 console.log('- BackgroundGeolocation is ready: ', state); 17} catch (error) { 18 console.warn('- BackgroundGeolocation error: ', error); 19}
A fully-featured Demo App is available in its own public repo. After first cloning that repo, follow the installation instructions in the README there. This demo-app includes a settings-screen allowing you to quickly experiment with all the different settings available for each platform.
A simple Node-based web-application with SQLite database is available for field-testing and performance analysis. If you're familiar with Node, you can have this server up-and-running in about one minute.
The MIT License (MIT)
Copyright (c) 2018 Chris Scott, Transistor Software
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
No vulnerabilities found.
Reason
30 commit(s) and 24 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
binaries present in source code
Details
Reason
Found 1/29 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More