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
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
- create-react-native-library for the initial setup
- All our contributors and users!
Made with ❤️ by vishal