0.1.5 â€Ē Published 8 months ago

react-native-geo-locator v0.1.5

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

🌍 react-native-geo-locator

npm version license

react-native-geo-locator is a powerful, lightweight, and customizable library for tracking user location in the background in React Native applications. It enables real-time geolocation updates even when the app is running in the background, making it perfect for a variety of location-based services.

🚀 Features

  • 📍 Track user location in the background
  • 🏃‍♂ïļ Detect motion and activity changes
  • 🔄 Listen to changes in location provider (e.g., GPS, network)
  • ⚙ïļ Highly configurable with options for desired accuracy, distance filtering, and more
  • 🔋 Battery-optimized for efficient power consumption
  • ðŸŠķ Lightweight implementation for minimal app size impact
  • ðŸĪ– Android support (iOS support coming soon!)

ðŸ“Ķ Installation

npm install react-native-geo-locator
# or
yarn add react-native-geo-locator

🛠 Setup

Android

Add the following permissions to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

iOS (Coming Soon)

iOS support is planned for future updates. Stay tuned!

🔧 Usage

Here's a quick example to get you started:

import React, { useState, useEffect, Component } from 'react';
import { View, Text, Switch, StyleSheet, Button } from 'react-native';
import BackgroundLocation from 'react-native-geo-locator';

// Functional Component Example
const FunctionalExample = () => {
  const [enabled, setEnabled] = useState(false);
  const [location, setLocation] = useState(null);
  const [activity, setActivity] = useState('unknown');

  useEffect(() => {
    // Configure the background location settings
    BackgroundLocation.configure({
      desiredAccuracy: 'HIGH',
      distanceFilter: 10,
      stopTimeout: 1,
      notificationTitle: 'Location Tracking',
      notificationDescription:
        'Your location is being tracked for demo purposes.',
    });

    // Set up event listeners
    const locationSubscription = BackgroundLocation.onLocation((location) => {
      console.log('New location:', location);
      setLocation(location);
    });

    const activitySubscription = BackgroundLocation.onActivityChange(
      (activity) => {
        console.log('Activity changed:', activity);
        setActivity(activity);
      }
    );

    // Clean up subscriptions
    return () => {
      locationSubscription.remove();
      activitySubscription.remove();
    };
  }, []);

  useEffect(() => {
    if (enabled) {
      BackgroundLocation.start();
    } else {
      BackgroundLocation.stop();
    }
  }, [enabled]);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Functional Component Example</Text>
      <Switch value={enabled} onValueChange={setEnabled} />
      <Text>Tracking: {enabled ? 'ON' : 'OFF'}</Text>
      {location && (
        <Text>
          Location: {location.latitude.toFixed(4)},{' '}
          {location.longitude.toFixed(4)}
        </Text>
      )}
      <Text>Activity: {activity}</Text>
    </View>
  );
};

// Class Component Example
class ClassExample extends Component {
  state = {
    enabled: false,
    location: null,
    activity: 'unknown',
  };

  componentDidMount() {
    BackgroundLocation.configure({
      desiredAccuracy: 'MEDIUM',
      distanceFilter: 50,
      stopTimeout: 5,
      notificationTitle: 'Background Tracking',
      notificationDescription: 'Your location is being monitored.',
    });

    this.locationSubscription = BackgroundLocation.onLocation(
      this.handleLocationChange
    );
    this.activitySubscription = BackgroundLocation.onActivityChange(
      this.handleActivityChange
    );
  }

  componentWillUnmount() {
    this.locationSubscription.remove();
    this.activitySubscription.remove();
  }

  handleLocationChange = (location) => {
    console.log('New location (class):', location);
    this.setState({ location });
  };

  handleActivityChange = (activity) => {
    console.log('Activity changed (class):', activity);
    this.setState({ activity });
  };

  toggleTracking = () => {
    this.setState(
      (prevState) => ({ enabled: !prevState.enabled }),
      () => {
        if (this.state.enabled) {
          BackgroundLocation.start();
        } else {
          BackgroundLocation.stop();
        }
      }
    );
  };

  render() {
    const { enabled, location, activity } = this.state;
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Class Component Example</Text>
        <Button
          title={enabled ? 'Stop Tracking' : 'Start Tracking'}
          onPress={this.toggleTracking}
        />
        <Text>Tracking: {enabled ? 'ON' : 'OFF'}</Text>
        {location && (
          <Text>
            Location: {location.latitude.toFixed(4)},{' '}
            {location.longitude.toFixed(4)}
          </Text>
        )}
        <Text>Activity: {activity}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
});

// Main App component
export default function App() {
  return (
    <View style={{ flex: 1 }}>
      <FunctionalExample />
      <ClassExample />
    </View>
  );
}

📚 API Reference

BackgroundLocation.configure(options)

Configures the background location settings.

OptionTypeDescriptionDefault
desiredAccuracyStringAccuracy level: 'HIGH', 'MEDIUM', 'LOW''LOW'
distanceFilterNumberMinimum distance (meters) for updates50
stopTimeoutNumberTime (minutes) to stop if stationary5
stopOnTerminateBooleanStop tracking on app terminationtrue
startOnBootBooleanStart tracking on device bootfalse
notificationTitleStringNotification title'App is running'
notificationDescriptionStringNotification description'Tracking your location'

Event Listeners

  • BackgroundLocation.onLocation(callback)
  • BackgroundLocation.onMotionChange(callback)
  • BackgroundLocation.onActivityChange(callback)
  • BackgroundLocation.onProviderChange(callback)

Control Methods

  • BackgroundLocation.start()
  • BackgroundLocation.stop()

🔋 Battery Optimization

react-native-geo-locator is designed with battery efficiency in mind. It uses intelligent algorithms to minimize battery drain while still providing accurate location updates. The library:

  • Adapts tracking frequency based on movement detection
  • Uses low-power location providers when high accuracy is not required
  • Implements efficient background processing to reduce CPU usage

ðŸŠķ Lightweight Implementation

Despite its powerful features, react-native-geo-locator maintains a small footprint:

  • Minimal impact on app size
  • Efficient memory usage
  • Quick initialization and low overhead

These characteristics make it an excellent choice for developers who need robust location tracking without sacrificing app performance.

🔜 Roadmap

  • iOS support
  • Geofencing capabilities
  • Enhanced battery optimization strategies
  • More customizable notification options

ðŸĪ Contributing

We welcome contributions! Please check out our contributing guide to learn more about how to get involved.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgements


Made with âĪïļ by vishal

abort-controlleracceptsacornacorn-jsxacorn-walkadd-streamagent-baseaggregate-errorajvanseransi-alignansi-escapesansi-fragmentsansi-regexansi-stylesanymatchappdirsjsargargparsearray-buffer-byte-lengtharray-ifyarray-includesarray-unionarray.prototype.findlastarray.prototype.flatarray.prototype.flatmaparray.prototype.maparray.prototype.tosortedarraybuffer.prototype.slicearrifyasapast-typesastral-regexasync-limiterasync-retryavailable-typed-arraysbabel-corebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-module-resolverbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-transform-flow-enumsbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbase64-jsbasic-ftpbefore-after-hookbig-integerblboxenbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-frombundle-namebytescacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litechalkchar-regexchardetchrome-launcherchromium-edge-launcherci-infocjs-module-lexerclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepcocollect-v8-coveragecolor-convertcolor-namecolorettecommand-existscommandercommondircompare-funccompressiblecompressionconcat-mapconcat-streamconfig-chainconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcore-js-compatcore-util-iscosmiconfigcosmiconfig-typescript-loadercreate-jestcreate-requirecross-spawncrypto-random-stringcsstypedargsdata-uri-to-bufferdata-view-bufferdata-view-byte-lengthdata-view-byte-offsetdateformatdayjsdebugdecamelizedecamelize-keysdecompress-responsededentdeep-extenddeep-isdeepmergedefault-browserdefault-browser-iddefaultsdefer-to-connectdefine-data-propertydefine-lazy-propdefine-propertiesdegeneratordeldenodeifydepddeprecationdestroydetect-newlinediffdiff-sequencesdir-globdoctrinedot-propeastasianwidthee-firstelectron-to-chromiumemitteryemoji-regexencodeurlend-of-streamenv-pathsenvinfoerror-exerror-stack-parsererrorhandleres-abstractes-array-method-boxes-properlyes-define-propertyes-errorses-get-iteratores-iterator-helperses-object-atomses-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslint-plugin-eslint-commentseslint-plugin-ft-floweslint-plugin-jesteslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimexecaexitexpectexponential-backoffexternal-editorfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfast-urifast-xml-parserfastqfb-watchmanfetch-blobfiguresfile-entry-cachefill-rangefinalhandlerfind-babel-configfind-cache-dirfind-upflat-cacheflattedflow-enums-runtimeflow-parserfor-eachform-data-encoderformdata-polyfillfreshfs-extrafs.realpathfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-pkg-repoget-streamget-symbol-descriptionget-urigit-raw-commitsgit-remote-origin-urlgit-semver-tagsgit-upgit-url-parsegitconfiglocalglobglob-parentglobal-dirsglobalsglobalthisglobbygopdgotgraceful-fsgraphemerhandlebarshard-rejectionhas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-yarnhasownhermes-estreehermes-parserhosted-git-infohtml-escaperhttp-cache-semanticshttp-errorshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthuman-signalsiconv-liteieee754ignoreimage-sizeimport-freshimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipip-addressis-absoluteis-argumentsis-array-bufferis-arrayishis-async-functionis-bigintis-boolean-objectis-callableis-ciis-core-moduleis-data-viewis-date-objectis-directoryis-dockeris-extglobis-finalizationregistryis-fullwidth-code-pointis-generator-fnis-generator-functionis-git-dirtyis-git-repositoryis-globis-inside-containeris-installed-globallyis-interactiveis-mapis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-regexis-relativeis-setis-shared-array-bufferis-sshis-streamis-stringis-symbolis-text-pathis-typed-arrayis-typedarrayis-unc-pathis-unicode-supportedis-weakmapis-weakrefis-weaksetis-windowsis-wslis-yarn-globalisarrayisexeisobjectissue-parseristanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsiterate-iteratoriterate-valueiterator.prototypejest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjoijs-tokensjs-yamljsbnjsc-androidjsc-safe-urljscodeshiftjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonparseJSONStreamjsx-ast-utilskeyvkind-ofkleurlatest-versionlevenlevnlighthouse-loggerlines-and-columnsload-json-filelocate-pathlodashlodash.camelcaselodash.capitalizelodash.debouncelodash.escaperegexplodash.isfunctionlodash.ismatchlodash.isplainobjectlodash.isstringlodash.kebabcaselodash.mergelodash.mergewithlodash.snakecaselodash.startcaselodash.throttlelodash.uniqlodash.uniqbylodash.upperfirstlog-symbolslogkittyloose-envifylowercase-keyslru-cachemacos-releasemake-dirmake-errormakeerrormap-objmarkymemoize-onemeowmerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-minify-tersermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsminipassmkdirpmodify-valuesmsmute-streamnatural-comparenatural-compare-litenegotiatorneo-asyncnetmasknew-github-release-urlnocachenode-abort-controllernode-dirnode-domexceptionnode-fetchnode-forgenode-int64node-releasesnode-stream-zipnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsob1object-assignobject-inspectobject-keysobject.assignobject.entriesobject.fromentriesobject.valueson-finishedon-headersonceonetimeopenoptionatororaos-nameos-tmpdirp-cancelablep-limitp-locatep-mapp-trypac-proxy-agentpac-resolverpackage-jsonparent-moduleparse-jsonparse-pathparse-urlparseurlpath-existspath-is-absolutepath-keypath-parsepath-scurrypath-typepicocolorspicomatchpifypiratespkg-dirpkg-uppossible-typed-array-namesprelude-lsprettier-linter-helperspretty-formatprocess-nextick-argspromisepromise.allsettledpromptsprop-typesproto-listprotocolsproxy-agentproxy-from-envpumppunycodepupapure-randqqueuequeue-microtaskquick-lrurange-parserrcreact-devtools-corereact-isreact-refreshread-pkgread-pkg-upreadable-streamreadlinerecastrechoirredentreflect.getprototypeofregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexp.prototype.flagsregexpu-coreregistry-auth-tokenregistry-urlregjsgenregjsparserrequire-directoryrequire-from-stringrequire-main-filenamereselectresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve.exportsresponselikerestore-cursorretryreusifyrimrafrun-applescriptrun-asyncrun-parallelrxjssafe-array-concatsafe-buffersafe-regex-testsafer-bufferschedulerselfsignedsemversemver-diffsendserialize-errorserve-staticset-blockingset-function-lengthset-function-namesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsside-channelsignal-exitsisteransislashslice-ansismart-buffersockssocks-proxy-agentsource-mapsource-map-supportspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit2sprintf-jsstack-utilsstackframestacktrace-parserstatusesstdin-discarderstop-iteration-iteratorstring-lengthstring-natural-comparestring-widthstring.prototype.matchallstring.prototype.repeatstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-bomstrip-final-newlinestrip-indentstrip-json-commentsstrnumsudo-promptsupports-colorsupports-preserve-symlinks-flagsynckittemptersertest-excludetext-extensionstext-tablethroatthroughthrough2titleizetmptmplto-fast-propertiesto-regex-rangetoidentifiertr46trim-newlinests-nodetslibtsutilsturbo-windows-64type-checktype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarraytypedarray-to-bufferuglify-jsunbox-primitiveunc-path-regexundici-typesunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunique-stringuniversal-user-agentuniversalifyunpipeuntildifyupdate-browserslist-dbupdate-notifieruri-jsurl-joinutil-deprecateutils-mergev8-compile-cache-libv8-to-istanbulvalidate-npm-package-licensevaryvlqvm2walkerwcwidthweb-streams-polyfillwebidl-conversionswhatwg-fetchwhatwg-urlwhichwhich-boxed-primitivewhich-builtin-typewhich-collectionwhich-modulewhich-typed-arraywidest-linewildcard-matchwindows-releaseword-wrapwordwrapwrap-ansiwrappywrite-file-atomicwsxdg-basedirxtendy18nyallistyamlyargsyargs-parserynyocto-queue
0.1.5

8 months ago

0.1.4

8 months ago

0.1.3

8 months ago

0.1.2

8 months ago

0.1.1

8 months ago

0.1.0

8 months ago