Create and manage geofences in React Native
react-native-geolocation-monitor uses iOS’s CoreLocation and Android’s location services to create and monitor circular geofences.
npm install react-native-geolocation-monitor --save
or using yarn:
yarn add react-native-geolocation-monitor
$ react-native link react-native-geolocation-monitor
Libraries
➜ Add Files to [your project's name]
node_modules
➜ react-native-geolocation-monitor
and add RNGeofence.xcodeproj
libRNGeofence.a
to your project’s Build Phases
➜ Link Binary With Libraries
Cmd+R
)android/app/src/main/java/[...]/MainApplication.java
import com.acurat.geofence.RNGeofencePackage;
to the imports at the top of the filenew RNGeofencePackage()
to the list returned by the getPackages()
methodandroid/settings.gradle
:
include ':react-native-geolocation-monitor'
project(':react-native-geolocation-monitor').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-geolocation-monitor/android')
android/app/build.gradle
:
implementation project(':react-native-geolocation-monitor')
In your AndroidManifest.xml
add the following
...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<receiver
android:name="com.acurat.geofence.RNGeofenceBroadcastReceiver"
android:enabled="true"
android:exported="true" ></receiver>
...
Add the NSLocationWhenInUseUsageDescription
key and the NSLocationAlwaysAndWhenInUseUsageDescription
key
to your Info.plist file.
(Xcode displays these keys as “Privacy - Location When In Use Usage Description” and
“Privacy - Location Always and When In Use Usage Description” in the Info.plist editor.)
If your app supports iOS 10 and earlier, add the NSLocationAlwaysUsageDescription
key to your Info.plist file.
(Xcode displays this key as “Privacy - Location Always Usage Description” in the Info.plist editor.)
If you need updates when the app is in background mode, add the following to your Info.plist
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Geofence, { Constants } from 'react-native-geolocation-monitor';
export default class App extends Component {
subscription;
componentDidMount() {
Geofence.initialize({ requestPermission: true });
Geofence.add({
id: 'work',
radius: 50,
latitude: 37.422611,
longitude: -122.0840577,
})
.then(result => console.warn(result))
.catch(error => console.warn(JSON.stringify(error)));
this.subscription = Geofence.notify(result => {
console.warn(result);
});
}
componentWillUnmount() {
if (this.subscription) {
this.subscription.remove();
}
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text>Basic Usage!</Text>
</View>
);
}
}
Initializes and requests permission from the user.
const params = {
requestPermission: true //Or false
};
RNGeofence.initialize(params);
RNGeofence.requestPermission()
must be called later if permission is not requested during initialization
Requests permission from the user.
RNGeofence.requestPermission();
Checks and returns true
if location permissions have been granted by the user. Else false
is returned.
RNGeofence.checkPermission().then(result => console.info(result));
// result is a boolean
Adds a circular region for monitoring. The promise resolves with an array of strings.
const region = {
id: 'work', // Unique identifier for the region, this is returned when a geofence transition occurs.
longitude: '-90.4436994',
latitude: '38.5419558',
radius: 100, // Optional, default: 50 meters
expirationDuration: 600000 // Optional in milliseconds, Android only, default: Never expires
};
RNGeofence.add(region).then(result => console.info(result));
// result is an String[] of one item containing Id
Adds multiple regions at once for monitoring. The promise resolves with an array of strings.
const regions = [{
id: 'work',
longitude: '-90.4436994',
latitude: '38.5419558',
radius: 100,
expirationDuration: ''
}, {
id: 'disneyWorld',
longitude: '-81.5660627',
latitude: '28.385233',
}];
RNGeofence.addAll(regions).then(result => console.info(result));
// result is an String[] containing Ids of successfully added regions
Remove a region from monitoring. The promise resolves with an array of strings.
RNGeofence.remove('work').then(result => console.info(result));
// result is an String[] containing Ids of successfully added regions
Removes multiple regions at once. The promise resolves with an array of strings.
RNGeofence.remove(['work', 'home']).then(result => console.info(result));
// result is an String[] containing Ids of successfully added regions
Clears all geofences. This returns a promise that resolves with a void.
RNGeofence.clear();
Counts all current geofences. Available only on iOS. The promise resolves with a number.
Android returns -1
RNGeofence.count()
.then(value => console.warn("# of regions currently monitored", value));
// value is a number
Provide a callback to notify that is called when a geofence transition occurs.
const subscription = Geofences.notify((response) => console.log(JSON.stringify(response)));
/*
response contains
{
transitionType: 'ENTER' | 'EXIT',
ids: string[] // Contains region ids that triggered transition
}
*/
// Be sure to `subscription.remove()` to avoid memory leaks (usually in `componentWillUnmount()`)