Git Product home page Git Product logo

transistorsoft / react-native-background-geolocation Goto Github PK

View Code? Open in Web Editor NEW
2.6K 59.0 427.0 788.08 MB

Sophisticated, battery-conscious background-geolocation with motion-detection

Home Page: http://shop.transistorsoft.com/pages/react-native-background-geolocation

License: MIT License

JavaScript 16.66% Objective-C 53.23% Ruby 0.35% Java 15.17% Shell 0.71% HTML 0.04% TypeScript 1.63% C++ 12.21%
react-native background-location background background-geolocation location-tracking

react-native-background-geolocation's Introduction

alt text Now with Expo support

Background Geolocation for React Native Β· npm npm


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.


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.

(2018) This plugin is supported full-time and field-tested daily since 2013.


Google Play

Home Settings

Contents

πŸ”· Installing the Plugin

With Expo

npx expo install react-native-background-geolocation

With yarn

yarn add react-native-background-geolocation

With npm

$ npm install react-native-background-geolocation --save

πŸ”· Setup Guides

Expo

iOS

Android

πŸ”· Configure your license

  1. Login to Customer Dashboard to generate an application key: www.transistorsoft.com/shop/customers

  2. Add your license-key to android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.transistorsoft.backgroundgeolocation.react">

  <application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:theme="@style/AppTheme">

    <!-- react-native-background-geolocation licence -->
+     <meta-data android:name="com.transistorsoft.locationmanager.license" android:value="YOUR_LICENCE_KEY_HERE" />
    .
    .
    .
  </application>
</manifest>

πŸ”· Using the plugin

import BackgroundGeolocation from "react-native-background-geolocation";

For those using Typescript (recommended), you can also import the interfaces:

import BackgroundGeolocation, {
  State,
  Config,
  Location,
  LocationError,
  Geofence,
  GeofenceEvent,
  GeofencesChangeEvent,
  HeartbeatEvent,
  HttpEvent,
  MotionActivityEvent,
  MotionChangeEvent,
  ProviderChangeEvent,
  ConnectivityChangeEvent
} from "react-native-background-geolocation";

For more information, see this blog post

πŸ”· Example

There are three main steps to using BackgroundGeolocation

  1. Wire up event-listeners.
  2. .ready(config) the plugin.
  3. .start() the plugin.

⚠️ 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
// NO!  .ready() has not resolved.
BackgroundGeolocation.getCurrentPosition(options);
BackgroundGeolocation.start();

BackgroundGeolocation.ready(config).then((state) => {
  // YES -- .ready() has now resolved.
  BackgroundGeolocation.getCurrentPosition(options);
  BackgroundGeolocation.start();  
});

// NO!  .ready() has not resolved.
BackgroundGeolocation.getCurrentPosition(options);
BackgroundGeolocation.start();

Example 1. β€” React Functional Component

Show Source
import React from 'react';
import {
  Switch,
  Text,
  View,
} from 'react-native';

import BackgroundGeolocation, {
  Location,
  Subscription
} from "react-native-background-geolocation";

const HelloWorld = () => {
  const [enabled, setEnabled] = React.useState(false);
  const [location, setLocation] = React.useState('');

  React.useEffect(() => {
    /// 1.  Subscribe to events.
    const onLocation:Subscription = BackgroundGeolocation.onLocation((location) => {
      console.log('[onLocation]', location);
      setLocation(JSON.stringify(location, null, 2));
    })

    const onMotionChange:Subscription = BackgroundGeolocation.onMotionChange((event) => {
      console.log('[onMotionChange]', event);
    });

    const onActivityChange:Subscription = BackgroundGeolocation.onActivityChange((event) => {
      console.log('[onActivityChange]', event);
    })

    const onProviderChange:Subscription = BackgroundGeolocation.onProviderChange((event) => {
      console.log('[onProviderChange]', event);
    })

    /// 2. ready the plugin.
    BackgroundGeolocation.ready({
      // Geolocation Config
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      // Activity Recognition
      stopTimeout: 5,
      // Application config
      debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when user closes the app.
      startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
      // HTTP / SQLite config
      url: 'http://yourserver.com/locations',
      batchSync: false,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
      autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
      headers: {              // <-- Optional HTTP headers
        "X-FOO": "bar"
      },
      params: {               // <-- Optional HTTP params
        "auth_token": "maybe_your_server_authenticates_via_token_YES?"
      }
    }).then((state) => {
      setEnabled(state.enabled)
      console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);
    });

    return () => {
      // Remove BackgroundGeolocation event-subscribers when the View is removed or refreshed
      // during development live-reload.  Without this, event-listeners will accumulate with
      // each refresh during live-reload.
      onLocation.remove();
      onMotionChange.remove();
      onActivityChange.remove();
      onProviderChange.remove();
    }
  }, []);

  /// 3. start / stop BackgroundGeolocation
  React.useEffect(() => {
    if (enabled) {
      BackgroundGeolocation.start();
    } else {
      BackgroundGeolocation.stop();
      setLocation('');
    }
  }, [enabled]);

  return (
    <View style={{alignItems:'center'}}>
      <Text>Click to enable BackgroundGeolocation</Text>
      <Switch value={enabled} onValueChange={setEnabled} />
      <Text style={{fontFamily:'monospace', fontSize:12}}>{location}</Text>
    </View>
  )
}

export default HelloWorld;

Example 2. β€” React Class Component

Show Source
import React from 'react';
import {
  Switch,
  Text,
  View,
} from 'react-native';

import BackgroundGeolocation, {
  Location,
  Subscription
} from "react-native-background-geolocation";

export default class HelloWorld extends React.Component {
  subscriptions:Subscription[] = [];
  state:any = {};
  constructor(props:any) {
    super(props);
    this.state = {
      enabled: false,
      location: ''
    }
  }

  componentDidMount() {
    /// 1.  Subscribe to BackgroundGeolocation events.
    this.subscriptions.push(BackgroundGeolocation.onLocation((location) => {
      console.log('[onLocation]', location);
      this.setState({location: JSON.stringify(location, null, 2)})
    }, (error) => {
      console.log('[onLocation] ERROR:', error);
    }))

    this.subscriptions.push(BackgroundGeolocation.onMotionChange((event) => {
      console.log('[onMotionChange]', event);
    }))

    this.subscriptions.push(BackgroundGeolocation.onActivityChange((event) => {
      console.log('[onActivityChange]', event);
    }))

    this.subscriptions.push(BackgroundGeolocation.onProviderChange((event) => {
      console.log('[onProviderChange]', event);
    }))

    /// 2. ready the plugin.
    BackgroundGeolocation.ready({
      // Geolocation Config
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      // Activity Recognition
      stopTimeout: 5,
      // Application config
      debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when user closes the app.
      startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
      // HTTP / SQLite config
      url: 'http://yourserver.com/locations',
      batchSync: false,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
      autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
      headers: {              // <-- Optional HTTP headers
        "X-FOO": "bar"
      },
      params: {               // <-- Optional HTTP params
        "auth_token": "maybe_your_server_authenticates_via_token_YES?"
      }
    }).then((state) => {
      this.setState({enabled: state.enabled});
      console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);
    })
  }

  /// When view is destroyed (or refreshed during development live-reload),
  /// remove BackgroundGeolocation event subscriptions.
  componentWillUnmount() {
    this.subscriptions.forEach((subscription) => subscription.remove());
  }

  onToggleEnabled(value:boolean) {
    console.log('[onToggleEnabled]', value);
    this.setState({enabled: value})
    if (value) {
      BackgroundGeolocation.start();
    } else {
      this.setState({location: ''});
      BackgroundGeolocation.stop();
    }
  }

  render() {
    return (
      <View style={{alignItems:'center'}}>
        <Text>Click to enable BackgroundGeolocation</Text>
        <Switch value={this.state.enabled} onValueChange={this.onToggleEnabled.bind(this)} />
        <Text style={{fontFamily:'monospace', fontSize:12}}>{this.state.location}</Text>
      </View>
    )
  }
}

Promise API

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

BackgroundGeolocation.ready({
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 
  distanceFilter: 50
}).then(state => {
  console.log('- BackgroundGeolocation is ready: ', state);
}).catch(error => {
  console.warn('- BackgroundGeolocation error: ', error);
});

// Or use await in an async function
try {
  const state = await BackgroundGeolocation.ready({
    desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 
    distanceFilter: 50
  })
  console.log('- BackgroundGeolocation is ready: ', state);
} catch (error) {
  console.warn('- BackgroundGeolocation error: ', error);
}

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.

Home Settings

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.

License

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.

react-native-background-geolocation's People

Contributors

alexgsummer avatar amejia49 avatar ascherkus avatar cgav avatar chestercharles avatar christocracy avatar dalerasrorov avatar davidhampgonsalves avatar dikarel avatar elieteyssedou avatar giacomocerquone avatar joenoon avatar jordanbyron avatar losnikitos avatar markrickert avatar matbrady avatar mikehardy avatar mlandauer avatar nevir avatar nicholascm avatar parkerdan avatar philippotto avatar pwellner avatar radko93 avatar shinout avatar tiaanduplessis avatar transistorsoft-pkg avatar vonkanehoffen avatar willbattel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-background-geolocation's Issues

Question

Hi,

I have a doubt about something :
I see it is possible to set up event listeners in the JS code but i was wondering if they would be triggered when the app is not open or when the phone is sleeping.
According to facebook/react-native#1282, i am not so sure :/
What is your experience about it?

Thank you

Followed installation instructions and got 'Lexical Preprocessor Issue'

I followed the iOS installation guide and received the following build failure errors:

/my_project/node_modules/react-native-background-geolocation/:1:1: Umbrella header for module 'TSLocationManager' does not include header 'Settings.h'

/steve/Roadwayz/node_modules/react-native-background-geolocation/:1:1: Umbrella header for module 'TSLocationManager' does not include header 'TSLogger.h'

Either there's something wrong with the component, or there's something not made clear in the installation instructions, I have no real experience with obj-c in iOS, so I don't know where to go from here.

change ios markers

how can i change the red location markers with the blue polyline ? I see the functions there to do it but I do not know if that is for android or ios? or both? I uncommented the function and was getting a error from the create method.

Failure while distributing app Archive (iOS)

Hi,
After creating an archive I want to distribute it Ad-Hoc, but I get an error:

2016-04-01 08:13:38 +0000 [MT] [OPTIONAL] Didn't find archived user entitlements for <DVTFilePath:0x7f85d34661e0:'/Users/jeroenb/Library/Developer/Xcode/Archives/2016-04-01/PTT 01-04-16 10.13.xcarchive/Products/Applications/PTT.app/Frameworks/TSLocationManager.framework'>: Error Domain=NSCocoaErrorDomain Code=4 "Item at "/Users/jeroenb/Library/Developer/Xcode/Archives/2016-04-01/PTT 01-04-16 10.13.xcarchive/Products/Applications/PTT.app/Frameworks/TSLocationManager.framework" did not contain a "archived-expanded-entitlements.xcent" resource." UserInfo={NSLocalizedDescription=Item at "/Users/jeroenb/Library/Developer/Xcode/Archives/2016-04-01/PTT 01-04-16 10.13.xcarchive/Products/Applications/PTT.app/Frameworks/TSLocationManager.framework" did not contain a "archived-expanded-entitlements.xcent" resource.}

Do you have any idea? I must say I changed provisioning profile as well, when looking at stackoverflow that might be the culprit.

I must admit I do not have any experience with testing iOS apps, and the whole XCode/Apple ecosystem is really really confusing

undefined is not an object (evaluating 'BackgroundGeolocationManager.configure')

Warning: I'm brand new to Android development. Please let me know what additional debug info might be useful.

I'm receiving the following error on Android emulator: undefined is not an object (evaluating 'BackgroundGeolocationManager.configure')

Is it curious that the error is referencing RNBackgroundGeolocation.ios.js?

screen shot 2015-10-28 at 10 05 07 am

I created my Android Virtual Device by following the instructions on the Android Setup page of the React Native docs.

Do I need to build a new one with Google Play services? (That's the only anomaly I can detect from reading the repo's wiki.)

I'm pretty much using the stock example:

componentDidMount() {

  BackgroundGeolocation.configure({
    desiredAccuracy: 0,
    stationaryRadius: 50,
    distanceFilter: 50,
    disableElasticity: false,             // <-- [iOS] Default is 'false'.  Set true to disable speed-based distanceFilter elasticity
    locationUpdateInterval: 5000,
    minimumActivityRecognitionConfidence: 80,   // 0-100%.  Minimum activity-confidence for a state-change
    fastestLocationUpdateInterval: 5000,
    activityRecognitionInterval: 10000,
    stopDetectionDelay: 1,                // <--  minutes to delay after motion stops before engaging stop-detection system
    stopTimeout: 2,                       // 2 minutes
    activityType: 'AutomotiveNavigation',

    // Application config
    debug: false,                         // <-- enable this hear sounds for background-geolocation life-cycle.
    forceReloadOnLocationChange: false,   // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a new location is recorded (WARNING: possibly distruptive to user)
    forceReloadOnMotionChange: false,     // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when device changes stationary-state (stationary->moving or vice-versa) --WARNING: possibly distruptive to user)
    forceReloadOnGeofence: false,         // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a geofence crossing occurs --WARNING: possibly distruptive to user)
    stopOnTerminate: false,               // <-- [Android] Allow the background-service to run headless when user closes the app.
    startOnBoot: true,                    // <-- [Android] Auto start background-service in headless mode when device is powered-up.

    // HTTP / SQLite config
    // url: 'http://posttestserver.com/post.php?dir=cordova-background-geolocation',
    // batchSync: true,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
    // autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
    // maxDaysToPersist: 1,    // <-- Maximum days to persist a location in plugin's SQLite database when HTTP fails
    // headers: {
    //   "X-FOO": "bar"
    // },
    // params: {
    //   "auth_token": "maybe_your_server_authenticates_via_token_YES?"
    // }
  });

  // This handler fires whenever bgGeo receives a location update.
  BackgroundGeolocation.on('location', location => {
    console.log('>>> BackgroundGeolocation location');
    this.setLocation(location);
  });

  // This handler fires when movement states changes (stationary->moving; moving->stationary)
  BackgroundGeolocation.on('motionchange', location => {
    console.log('>>> BackgroundGeolocation motionchange');
    this.setLocation(location);
  });

  BackgroundGeolocation.start(() => {
    console.log('>>> BackgroundGeolocation start');

    // Fetch current position
    BackgroundGeolocation.getCurrentPosition(location => {
      console.log('>>> BackgroundGeolocation getCurrentPosition');
      this.setLocation(location);
    }, GEO_CONFIG);
  });

}

location change event stops firing after about 24 hours

Hi there,

We've been testing this library on iOS and are configured with preventSuspend: true and a heartbeatInterval of 60. Everything functions as expected for about 24 hours and then the location events stop firing.

Is this because we're using preventSuspend? Have you noticed this when the app is inactive for more than a few days in the background?

Thanks!

Can't export or upload app

Whenever I try to export the app, I get an error that says Found an unexpected Mach-O header code: 0x72613c21

here are the logs:

//critical.log
2016-03-13 18:07:40 +0000 [MT] Failed to generate distribution items with error: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo={NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=}
2016-03-13 18:07:40 +0000 [MT] Presenting: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo={NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=}
//standard.log
2016-03-13 18:07:39 +0000 [MT] Beginning distribution assistant for archive: Freezetag, task: Export
2016-03-13 18:07:40 +0000 [MT] Proceeding to distribution step IDEDistributionSigningAssetsStepViewController, context: <IDEDistributionContext: 0x7fd7be155350; archive(resolved)='<IDEArchive: 0x7fd7bcb8bd10>', distributionTask(resolved)='2', distributionMethod(resolved)='<IDEDistributionMethodiOSAppStoreExport: 0x7fd7bc12ba80>', teamID(resolved)='(null)'>
    Chain (2, self inclusive):
    <IDEDistributionContext: 0x7fd7be155350; archive = '(null)', distributionMethod='(null)', teamID='(null)'>
    <IDEDistributionContext: 0x7fd7bfa195b0; archive = '<IDEArchive: 0x7fd7bcb8bd10>', distributionMethod='<IDEDistributionMethodiOSAppStoreExport: 0x7fd7bc12ba80>', teamID='(null)'>
</IDEDistributionContext: 0x7fd7be155350>
2016-03-13 18:07:40 +0000 [MT] [OPTIONAL] Didn't find archived user entitlements for <DVTFilePath:0x7fd7c09da7a0:'/Users/Yonah/Library/Developer/Xcode/Archives/2016-03-13/Freezetag 13-03-16 18.46.xcarchive/Products/Applications/Freezetag.app/Frameworks/TSLocationManager.framework'>: Error Domain=NSCocoaErrorDomain Code=4 "Item at "/Users/Yonah/Library/Developer/Xcode/Archives/2016-03-13/Freezetag 13-03-16 18.46.xcarchive/Products/Applications/Freezetag.app/Frameworks/TSLocationManager.framework" did not contain a "archived-expanded-entitlements.xcent" resource." UserInfo={NSLocalizedDescription=Item at "/Users/Yonah/Library/Developer/Xcode/Archives/2016-03-13/Freezetag 13-03-16 18.46.xcarchive/Products/Applications/Freezetag.app/Frameworks/TSLocationManager.framework" did not contain a "archived-expanded-entitlements.xcent" resource.}
2016-03-13 18:07:53 +0000 [MT] Canceled distribution assistant
//verbose.log
2016-03-13 18:07:39 +0000 [MT] Available distribution methods: (
    "<IDEDistributionMethodiOSAppStoreExport: 0x7fd7bc12ba80>",
    "<IDEDistributionMethodAdHoc: 0x7fd7bc12cf10>",
    "<IDEDistributionMethodEnterprise: 0x7fd7bc12e180>",
    "<IDEDistributionMethodDevelopmentSigned: 0x7fd7bc12d6a0>"
)
2016-03-13 18:07:40 +0000 [MT] IDEDistributionItem init <DVTFilePath:0x7fd7c09da7a0:'/Users/Yonah/Library/Developer/Xcode/Archives/2016-03-13/Freezetag 13-03-16 18.46.xcarchive/Products/Applications/Freezetag.app/Frameworks/TSLocationManager.framework'>

Couple of Questions

This module looks awesome! couple of questions:

  1. Is this module free to use? I see it is licensed MIT but I also see on your page that you sell a similar product?
  2. You mention android in the docs, but react-native android is not out yet. Are these just placeholders for how it will work once react-native android is released?

setConfig() callback

The documentation is inconsistent on whether or not setConfig() accepts a callback. Probably c/p from the configure() method.

image

EDIT: just saw a pull request which addresses the issue #88

While we're at it, does it need a callback? Is the new configuration applied synchronously somehow even while the plugin is tracking device location?

locationUpdateInterval for iOS

Is there no locationUpdateInterval in the iOS version?
For my use case it is completely sufficient to send the location data every 5-10s to the server. But iOS seems to be updating the location way more often. I know there is the distanceFilter, but I'd rather sample per time than per distance-change.

Android is ready.

The android bindings are nearly ready. It's all working, just need to test it out a bit and whip up a Sample application.

Should be available this Friday, November 6.

toggle logging

is there a way to toggle the logging information in the xcode debug area

Access to motion and fitness data

When I start my app it asks for a permission to access motion and fitness data. Why is this necessary? Is there a way to avoid it?

Implementation/Example?

This is exactly what I have been looking for!

Can you provide an example or instructions for implementing this in a current react-native build (or new build)?

Again, I am very excited to see this in action. Thank you!

-Tim

npm install not working with v4.0.0

I just tried installing the plugin and at first I got:

module.js:338
    throw err;
    ^

Error: Cannot find module 'npmlog'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:18:11
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:75:3)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

By changing to node version v0.12.7 the installation worked, so I assume there is a problem when installing this package with node v4.0.0

Getting location to work when app is killed

Hi,

Everything seems to be working fine on Android but I can't figure out how to make my app keep track of the position after it has been killed (double press home + swipe). Is it possible or am I mistaken? I couldn't get it to work either on device nor in the emulator with "Freeway drive".

This is my initialization code:

var startBgGeoloc = function () {
    Storage.getUserProperty("token").then(token => {
        var options = {
            debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.

            // common
            desiredAccuracy: 10,
            distanceFilter: 100,
            stopOnTerminate: false,
            activityRecognitionInterval: 10000,
            stopTimeout: 2, // 2 minutes

            // iOS
            stationaryRadius: 100, // restart tracking after the user has moved 100m
            activityType: "AutomotiveNavigation",
            useSignificantChangesOnly: false,

            // Android
            startOnBoot: true,
            locationUpdateInterval: 5 * 60 * 1000,
            fastestLocationUpdateInterval: 60 * 1000,
            forceReloadOnLocationChange: false,  // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a new location is recorded (WARNING: possibly distruptive to user)
            forceReloadOnMotionChange: false,    // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when device changes stationary-state (stationary->moving or vice-versa) --WARNING: possibly distruptive to user)
            forceReloadOnGeofence: false,        // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a geofence crossing occurs --WARNING: possibly distruptive to user)

            // HTTP / SQLite config
            url: Server.SERVER_URL + "/tracking-locations/",
            batchSync: false,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
            autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
            maxDaysToPersist: 1,    // <-- Maximum days to persist a location in plugin"s SQLite database when HTTP fails
            headers: {
                "Authorization": `Token ${token}`
            },
            params: {
            }
        };

        BackgroundGeolocation.configure(options);
        BackgroundGeolocation.setOptions(options);

        BackgroundGeolocation.start(() => {
            Log.debug("[BackgroundGeolocation] started successfully");

            // Fetch current position
            BackgroundGeolocation.getCurrentPosition({timeout: 30}, (location) => {
                Log.debug("[BackgroundGeolocation] received current position: ", JSON.stringify(location));
            }, (error) => {
                alert("Location error: " + error);
            });
        });
    });
};

Getting geolocation status

Hi, is there a way to tell if the plugin is currently working (getting positions)?

I want to have a settings screen where the user can disable the tracking, so I'd like to be able to get the current status. It could be as simple as an item in .getState(), that would return {active: true|false}.

Thanks!

Add #clear and #setExtras methods

Hi Chris,

It would be great to have a #clear method to allow us to clear the local DB without syncing to the server.

Also, it would be nice to have a method (like #setExtras) that allow's us to add extra custom properties to the location markers before they are stored to the local DB.

The use case for me would be storing data for multiple trips, and being able to view that data separately on the device even if the user doesn't have a connection to the server. Also, users without accounts may not have the ability to store a trip history, but they could track one trip at a time (and therefore would need to clear the DB without syncing to the server).

Thanks again!

James

Step 9 Framework Search Path build error

After going through all the installation step and doing exactly what have ben instructed I ran into a problem in the last step unfortunately.
When it is instructed to add $(PROJECT_DIR)/../node_modules/react-native-background-geolocation to Framework Search Paths which was totaly empty, I added $(PROJECT_DIR) and $(PROJECT_DIR)/../node_modules/react-native-background-geolocation and have set both to recurisve. But the screenshot that is in the installation guide has 3 properties instead of the one that was told to add to Framework Search Paths. When I try to build, the build success notification pops up but then an error popup message shows up which can be seen in the screenshot below. Any idea what have I done wrong?

Image of error

getGeofences doesn't return as documented

getGeofences returns a geofence per argument instead of an array of geofences as its first argument.

getGeofences(function(geofence1, geofence2, geofence3, etc...) {
  ...
});

instead of

getGeofences(function(geofences) {
  ...
});

In the react export on the objectiveC side the callback function expects an array of arguments, you're just giving it an array of geofences.

react native ^0.18.0-rc npm i error

Have this error on installation

➜  spot git:(master) βœ— npm i react-native-background-geolocation       
npm WARN peerDependencies The peer dependency react-native@>=0.8.0 included from react-native-background-geolocation will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency 
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.
npm ERR! Darwin 15.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "i" "react-native-background-geolocation"
npm ERR! node v4.2.4
npm ERR! npm  v2.14.15
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react-native@>=0.8.0

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/butuzgol/Playground/spot/npm-debug.log

ld: framework not found TSLocationManager clang: error: linker command failed

Getting this error when trying to do a fresh install & build running RN v0.22 and Xcode 7.3. I am noticing that in my Xcode I only see 'Header Search Paths', not 'Framework Search Paths', and therefore cannot add it to "Framework Search Paths". Guessing this could be the issue. Any idea how I can add a record for framework search paths?

image

image

Also, your installation instructions are not totally clear. At one point you mention finding a dependency in RCTMapboxGL but there is no indication that this needs to be installed. I believe it's a typo in your path indication.
image

Thank you.

Can't run the application on a device.

I created React Native init project and followed installation instructions. It's worked well on simulator, but when I run on iPhone, Xcode shows error message "App installation failed. The application does not have a valid signature.". The same story with your demo app.

It looks like issue with provisioning profiles and related stuff, but I have no idea how to fix it. There weren't any problems with other React Native packages.

Do you have any idea how can I handle this?

on('location') event not being fired using ios simulator

Hey there, i'm trying to get this up and running but the BackgroundGeolocation.on('location', function(location) {}); event isn't being fired when using the ios simulator and Debug > Location > 'Freeway Drive' . I am using your example here. When the component loads I get some initial data (without error) in the debug console but i'm not getting a location update event. The initial data looks like this:

- onMotionChanage: {
    activity =     {
        confidence = 100;
        type = unknown;
    };
    battery =     {
        "is_charging" = 0;
        level = "-1";
    };
    coords =     {
        accuracy = 5;
        altitude = 0;
        altitudeAccuracy = "-1";
        heading = "292.15";
        latitude = "37.41152166";
        longitude = "-122.20187338";
        speed = "34.93";
    };
    "is_heartbeat" = 0;
    "is_moving" = 0;
    timestamp = "2016-02-08T05:21:43.103Z";
    uuid = "6CBCE52E-F7B9-4E33-87BB-2B955BA5C525";
}
RCTLog.js:38 - RCTBackgroundGeoLocation onLocationChanged
Track.js:56 - [js]location:  {"coords":{"speed":34.93,"longitude":-122.20187338,"latitude":37.41152166,"accuracy":5,"heading":292.15,"altitude":0,"altitudeAccuracy":-1},"is_heartbeat":false,"is_moving":false,"uuid":"F06094EC-9798-42A8-AA79-75E455DC2AF1","activity":{"type":"unknown","confidence":100},"battery":{"level":-1,"is_charging":0},"timestamp":"2016-02-08T05:21:43.103Z"}
Track.js:62 - Location: {"coords":{"speed":34.93,"longitude":-122.20187338,"latitude":37.41152166,"accuracy":5,"heading":292.15,"altitude":0,"altitudeAccuracy":-1},"is_heartbeat":false,"is_moving":false,"uuid":"F06094EC-9798-42A8-AA79-75E455DC2AF1","activity":{"type":"unknown","confidence":100},"battery":{"level":-1,"is_charging":0},"timestamp":"2016-02-08T05:21:43.103Z"}
RCTLog.js:38 - onHttpResponse
RCTLog.js:38 - onSyncComplete

My component looks like this: http://pastebin.com/Mg2CUrzP

When using the default ios navigator.geolocation.watchPosition(); I receive updates. Any ideas on what might be preventing the update event from firing?

Thank you. This looks like a great component, and i'm excited to integrate further :)

getCurrentPosition not being fired

Hello,

When I try to get the current location (on simulator, with "Custom location" defined), it does not seem to work (react-native 0.25)

componentDidMount() {
  geolocation.start()
  geolocation.getCurrentPosition(() => {
    console.info('it works')
  })
}

The plugin seems correctly configured as I can see this in the devtools:

- RCTBackgroundGeolocation #configure
- RCTBackgroundGeoLocation #start

getCurrentPosition with error 100

I have an iPhone 5 with No service I am using to test my app along with several beta tester with iPhone 5s. I do not receive an failure callback in the designated timeout. I do however receive an error 100 randomly after this call anywhere between 1 minute and up to 8 minutes usually till indefinitely. I have also written another simple location library that gets the current location of the device and that works. Meaning that the GPS does have a current location. Seems like the timeout for the error 100 isn't timing out?

BackgroundGeolocation.getCurrentPosition({
persist: true,
timeout: 10, // 30 second timeout to fetch location
maximumAge: 5000, // Accept the last-known-location if not older than 5000 ms.
minimumAccuracy: 50, // Fetch a location with a minimum accuracy of 10 meters.
}, function(location) {
// This location is already persisted to plugin’s SQLite db.
// If you’ve configured #autoSync: true, the HTTP POST has already started.
console.log('- Current position received: ', location);
}, function(errorCode) {
alert('An location error occurred: ' + errorCode + ' ');
});

Incorrect wiki link in README.md

In README.md, under the heading 'Help, It doesn't work!' there is an incorrect link.

'See the wiki' points to

https://github.com/transistorsoft/cordova-background-geolocation/wiki

whereas, it should be

https://github.com/transistorsoft/react-native-background-geolocation/wiki

simulator crashes with HTTP sync turned on

Simulator recently started crashing when I have the HTTP sync enabled. Doesn't crash when running on the device. Not sure what other info i can provide. Here's a screenshot of the debugger. Is there a way to export crash reports?

screen shot 2016-06-10 at 10 29 38

maxRecordsToPersist doesn't appear to be honored

(latest version)

I'm attempting to disable persistence (we're not using it) by setting maxRecordsToPersist to 0. RNBG doesn't seem to honor this (event count keeps growing). Same behavior when setting it to 1.


Aside: Is a certain amount of history necessary for RNBG during regular operation?

Debugging config

Hi

I have spent the last two days trying every possible configuration and setup, installing the 0.4.1 and the 0.4.3 but I always endup with - [js] BackgroundGeolocation started successfully (a log I took from the demo app)

I have no idea where to start looking why it is not working. I got it working last week and don't know what I changed.

Do you have some steps to check what is causing the configure to fail? Or more in detail: why is the state.enable in the configure callback false? When I inspect the state object itself I cannot find errors or such.

We also bought the android version which is working in the emulator but not on an actual device. But I would lik to get it working on iOS first before moving on.

Thank you for your input!

Location Post schema when batchSync is true

Hi Chris,
location prop seems to be Array instead of object.

According to documentation about HTTP Post Schema, I would expect that in case of batchSync true the schema will look like:

[
{
    "location": {
        "coords": {
            "latitude":   [Float],
            "longitude":  [Float]
            "accuracy":   [Float]
            "speed":      [Float],
            "heading":    [Float],
            "altitude":   [Float]
        },
        "activity": {                
            "type": [still|on_foot|walking|running|in_vehicle|on_bicycle],
            "confidence": [0-100%]
        },
        "battery": {
            "level": [Float],
            "is_charging": [Boolean]
        },
        "timestamp": [ISO-8601 UTC], // eg:  "2015-05-05T04:31:54Z"
        "is_moving": [Boolean]       // <-- The motion-state when location was recorded.
    }
}
]

But in reality it is:

[
{
    "location": [{
        "coords": {
            "latitude":   [Float],
            "longitude":  [Float]
            "accuracy":   [Float]
            "speed":      [Float],
            "heading":    [Float],
            "altitude":   [Float]
        },
        "activity": {                
            "type": [still|on_foot|walking|running|in_vehicle|on_bicycle],
            "confidence": [0-100%]
        },
        "battery": {
            "level": [Float],
            "is_charging": [Boolean]
        },
        "timestamp": [ISO-8601 UTC], // eg:  "2015-05-05T04:31:54Z"
        "is_moving": [Boolean]       // <-- The motion-state when location was recorded.
    }]
} 
]

Setting useSignificantChangesOnly to true

This is not a bug, but it is not mentioned in the documentation, at least I couldn't find it.

Testing location tracking in the iOS simulator works fine using the Debug/Location menu.

But as soon as I turn on useSignificantChangesOnly I don't get any location updates anymore at all.
My guess is this is because useSignificantChangesOnly tracks change of cell towers which is not possible in the simulator.

Is this true?

Align Android / iOS JSON post

Hi

I noticed that the Android and iOS HTTP posts are different. A particular difference is the is_charging property of the battery.

iOS treats it as an integer and Android as a boolean. Could you align both libraries? I have golang app that is handling the responses and it is difficult to have different data types for each platform, for the same property.

Background tasks

Hi

I have a question regarding the background mode. Is it possible to track geolocations even when the app is killed? My client would like this and apparently Foursquare does that... I thought it was not possible and very intrusive. But it is possible :) Can the plugin do this too?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.