Skip to main content

Capacitor Plugin

This is the documentation for the Capacitor plugin. Before integrating, read the native SDK documentation to familiarize yourself with the platform.

See the source on GitHub here. Or, see the capacitor-radar package on npm here.

Install#

Install the package from npm:

npm install --save capacitor-radar

Then, update dependencies:

npx cap sync

If successful, you will see:

✔ Updating Android plugins  Found 1 Capacitor plugin for android:    capacitor-radar✔ update android...✔ Updating iOS plugins  Found 1 Capacitor plugin for ios:    capacitor-radar✔ Updating iOS native dependencies with "pod install" (may take several minutes)✔ update ios

Before writing any JavaScript, you must integrate the Radar SDK with your iOS and Android apps as described in the iOS SDK documentation and Android SDK documentation.

iOS#

You must add location usage descriptions and background modes to your Info.plist. For foreground permissions, you must add a value for NSLocationWhenInUseUsageDescription (Privacy - Location When In Use Usage Description). For background permissions, you must add a value for NSLocationAlwaysAndWhenInUseUsageDescription (Privacy - Location Always and When In Use Usage Description). These strings are displayed in permissions prompts.

If you are planning to leverage background tracking, such as responsive or continuous mode, in your project settings, go to Signing & Capabilities, add Background Modes, and turn on Background fetch and Location updates. Note that this requires additional justification during App Store review. Learn more.

Add the SDK to your project, preferably using CocoaPods. Finally, initialize the SDK in application:didFinishLaunchingWithOptions: in AppDelegate.swift, passing in your Radar publishable API key:

import Capacitorimport RadarSDK
@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {    Radar.initialize(publishableKey: publishableKey)
    return true  }
}

Android#

You must add Google Play Services Location to your project (use version 21.0.1 or higher).

implementation "com.google.android.gms:play-services-location:21.0.1"

Make sure that the Android SDK version matches the version in the radar-capacitor module's build.gradle.

Add the SDK to your project, preferably using Gradle. Finally, initialize the SDK and the plugin in onCreate() in MainActivity.java, passing in your Radar publishable API key:

import android.os.Bundle;
import com.getcapacitor.BridgeActivity;import io.radar.sdk.Radar;
public class MainActivity extends BridgeActivity {
  @Override  public void onCreate(Bundle savedInstanceState) {    Radar.initialize(this, publishableKey);
    super.onCreate(savedInstanceState);  }
}

For background tracking without a foreground service, and if targeting API level 29 or higher, Radar also requires the ACCESS_BACKGROUND_LOCATION permission. You must add the ACCESS_BACKGROUND_LOCATION permission to your manifest manually:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
</manifest>

Integrate#

Import module#

First, import the module:

import { Radar } from 'capacitor-radar';

Identify user#

To identify the user when logged in, call:

Radar.setUserId(userId);

where userId is a stable unique ID for the user.

To set an optional dictionary of custom metadata for the user, call:

Radar.setMetadata(metadata);

where metadata is a JSON object with up to 16 keys and values of type string, boolean, or number.

Finally, to set an optional description for the user, displayed in the dashboard, call:

Radar.setDescription(description);

where description is a string.

You only need to call these functions once, as these settings will be persisted across app sessions.

Learn about platform-specific implementations of these functions in the iOS SDK documentation and Android SDK documentation.

Request permissions#

Before tracking the user's location, the user must have granted location permissions for the app.

To determine the whether user has granted location permissions for the app, call:

Radar.getLocationPermissionsStatus().then((result) => {  // do something with result.status});

result.status will be a string, one of:

  • GRANTED_BACKGROUND
  • GRANTED_FOREGROUND
  • NOT_DETERMINED
  • DENIED

To request location permissions for the app, call:

Radar.requestLocationPermissions({ background: true });

where background is a boolean indicating whether to request background location permissions or foreground location permissions.

Learn about platform-specific permissions in the iOS SDK documentation and Android SDK documentation.

Foreground tracking#

Once you have initialized the SDK and the user has granted permissions, you can track the user's location.

To track the user's location in the foreground, call:

Radar.trackOnce().then((result) => {  // do something with result.location, result.events, result.user.geofences}).catch((err) => {  // optionally, do something with err});

err will be a string, one of:

  • ERROR_PUBLISHABLE_KEY: SDK not initialized
  • ERROR_PERMISSIONS: location permissions not granted
  • ERROR_LOCATION: location services error or timeout (10 seconds)
  • ERROR_NETWORK: network error or timeout (10 seconds)
  • ERROR_BAD_REQUEST: bad request (missing or invalid params)
  • ERROR_UNAUTHORIZED: unauthorized (invalid API key)
  • ERROR_PAYMENT_REQUIRED: payment required (organization disabled or usage exceeded)
  • ERROR_FORBIDDEN: forbidden (insufficient permissions or no beta access)
  • ERROR_NOT_FOUND: not found
  • ERROR_RATE_LIMIT: too many requests (rate limit exceeded)
  • ERROR_SERVER: internal server error
  • ERROR_UNKNOWN: unknown error

Learn about platform-specific implementations of this function in the iOS SDK documentation and Android SDK documentation.

Background tracking#

On iOS and Android, once you have initialized the SDK and the user has granted permissions, you can start tracking the user's location in the background.

For background tracking, the SDK supports custom tracking options as well as three presets:

  • EFFICIENT: A low frequency of location updates and lowest battery usage. On Android, avoids Android vitals bad behavior thresholds.
  • RESPONSIVE: A medium frequency of location updates and low battery usage. Suitable for most consumer use cases.
  • CONTINUOUS: A high frequency of location updates and higher battery usage. Suitable for on-demand use cases (e.g., delivery tracking) and some consumer use cases (e.g., order ahead, "mall mode").

Learn about platform-specific implementations of these presets in the iOS SDK documentation and Android SDK documentation.

To start tracking the user's location in the background, call one of:

Radar.startTrackingEfficient();
Radar.startTrackingResponsive();
Radar.startTrackingContinuous();

You only need to call these methods once, as these settings will be persisted across app sessions.

Though we recommend using presets for most use cases, you can customize the tracking options. See the tracking options reference.

// optionally adjust foreground service options for androidRadar.setForegroundServiceOptions({  options: {    text: "Location tracking started",    title: "Location updates",    updatesOnly: false,    importance: 2,    activity: 'com.yourapp.MainActivity'  }});
Radar.startTrackingCustom({  options: {    desiredStoppedUpdateInterval: 180,    fastestStoppedUpdateInterval: 15,    desiredMovingUpdateInterval: 60,    fastestMovingUpdateInterval: 15,    desiredSyncInterval: 10,    desiredAccuracy: 'high',    stopDuration: 140,    stopDistance: 70,    sync: 'all',    replay: 'none',    useStoppedGeofence: true,    showBlueBar: true,    foregroundServiceEnabled: true  }});

To stop tracking the user's location in the background (e.g., when the user logs out), call:

Radar.stopTracking();

Learn about platform-specific implementations of these functions in the iOS SDK documentation and Android SDK documentation.

To listen for events, location updates, and errors, you can add event listeners:

Radar.addListener('clientLocation', (result) => {  // do something with result.location, result.stopped, result.source});
Radar.addListener('location', (result) => {  // do something with result.location, result.user});
Radar.addListener('events', (result) => {  // do something with result.events, result.user});
Radar.addListener('error', (result) => {  // do something with result.err});
Radar.addListener('log', (result) => {  // do something with result.message});

Add event listeners outside of your view lifecycle if you want them to work when the app is in the background. Capacitor event listeners will only fire while the Capacitor WebView and JavaScript engine are alive. When the Android activity is killed (e.g., swiped away), these services will shut down. To process locations in the background, implement the native event emitters (RadarDelegate on iOS, RadarReceiver on Android) or use Radar's server-side integrations.

Mock tracking#

On iOS and Android, you can simulate a sequence of location updates for testing. For example, to simulate a sequence of 10 location updates every 3 seconds by car from an origin to a destination, we can call:

Radar.mockTracking({  origin: {    latitude: 40.714708,    longitude: -74.035807  },  destination: {    latitude: 40.717410,    longitude: -74.053334  },  mode: 'car',  steps: 10,  interval: 3});

Trip tracking#

To start a trip to a destination, call:

Radar.startTrip(options: {  tripOptions: {    externalId: '299',    destinationGeofenceTag: 'store',    destinationGeofenceExternalId: '123',    mode: 'car' as RadarRouteMode  },  trackingOptions: {    desiredStoppedUpdateInterval: 30,    fastestStoppedUpdateInterval: 30,    desiredMovingUpdateInterval: 30,    fastestMovingUpdateInterval: 30,    desiredSyncInterval: 20,    desiredAccuracy: 'high' as RadarTrackingOptionsDesiredAccuracy,    stopDuration: 0,    stopDistance: 0,    replay: "none",    sync: "all",    showBlueBar: true,    syncGeofences: false,    syncGeofencesLimit: 0,    beacons: false,    foregroundServiceEnabled: true  }}).then((result) => {  // do something with result.status});

Later, complete the trip by calling:

Radar.completeTrip().then((result) => {  // do something with result.status});

Or cancel the trip by calling:

Radar.cancelTrip().then((result) => {  // do something with result.status});

If tracking was disabled before the trip started, it will stop after the trip ends. Otherwise, it will revert to the tracking options in use before the trip started.

Learn more about trip tracking.

Manual tracking#

You can manually update the user's location by calling:

Radar.trackOnce({  latitude: 39.2904,  longitude: -76.6122,  accuracy: 65}, (result) => {  // do something with result.status, result.location, result.events, result.user});

Learn about platform-specific implementation of this function in the iOS SDK documentation and Android SDK documentation.

Other APIs#

The Capacitor plugin also exposes APIs for anonymous context, geocoding, search, and distance.

Get location#

Get a single location update without sending it to the server:

Radar.getLocation((result) => {  // do something with result.status, result.location});

Context#

With the context API, get context for a location without sending device or user identifiers to the server:

Radar.getContext({  latitude: 40.783826,  longitude: -73.975363,  accuracy: 65}, (result) => {  // do something with result.status, result.context});

Geocoding#

With the forward geocoding API, geocode an address, converting address to coordinates:

Radar.geocode({  query: '20 jay st brooklyn ny'}, (result) => {  // do something with result.status, result.addresses});

With the reverse geocoding API, reverse geocode a location, converting coordinates to address:

Radar.reverseGeocode({  latitude: 40.783826,  longitude: -73.975363}, (result) => {  // do something with result.status, result.addresses});

With the IP geocoding API, geocode the device's current IP address, converting IP address to city, state, and country:

Radar.ipGeocode((result) => {  // do something with result.status, result.address});

Search#

With the autocomplete API, autocomplete partial addresses and place names, sorted by relevance:

Radar.autocomplete({  query: 'brooklyn roasting',  near: {    latitude: 40.783826,    longitude: -73.975363  },  limit: 10}, (result) => {  // do something with result.status, result.addresses});

With the geofence search API, search for geofences near a location, sorted by distance:

Radar.searchGeofences({  radius: 1000,  tags: ['venue'],  limit: 10}, (result) => {  // do something with result.status, result.geofences});

With the places search API, search for places near a location, sorted by distance:

Radar.searchPlaces({  near: {    latitude: 40.783826,    longitude: -73.975363  },  radius: 1000,  chains: ['starbucks'],  limit: 10}, (result) => {  // do something with result.status, result.places});

Distance#

With the distance API, calculate the travel distance and duration from an origin to a destination:

Radar.getDistance({  origin: {    latitude: 40.78382,    longitude: -73.97536  },  destination: {    latitude: 40.70390,    longitude: -73.98670  },  modes: [    'foot',    'car'  ],  units: 'imperial'}, (result) => {  // do something with result.status, result.routes});

Support#

Have questions? We're here to help! Email us at support@radar.com.