npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-native-geo-locator

v0.1.5

Published

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

Downloads

328

Readme

🌍 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.

| Option | Type | Description | Default | | ------------------------- | ------- | --------------------------------------- | ------------------------ | | desiredAccuracy | String | Accuracy level: 'HIGH', 'MEDIUM', 'LOW' | 'LOW' | | distanceFilter | Number | Minimum distance (meters) for updates | 50 | | stopTimeout | Number | Time (minutes) to stop if stationary | 5 | | stopOnTerminate | Boolean | Stop tracking on app termination | true | | startOnBoot | Boolean | Start tracking on device boot | false | | notificationTitle | String | Notification title | 'App is running' | | notificationDescription | String | Notification 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