> ## Documentation Index
> Fetch the complete documentation index at: https://radarlabs-boon-update-faq-question-marks.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cordova plugin

This is the documentation for the Cordova plugin. Before integrating, read the [native SDK documentation](https://docs.radar.com/sdk) to familiarize yourself with the platform.

See the source on GitHub [here](https://github.com/radarlabs/cordova-plugin-radar). Or, see the `@radarlabs/cordova-plugin-radar` package on npm [here](https://www.npmjs.com/package/@radarlabs/cordova-plugin-radar).

## Install

Install the Cordova plugin:

```javascript
cordova plugin add @radarlabs/cordova-plugin-radar
```

Before writing any JavaScript, you must integrate the Radar SDK with your iOS and Android apps as described in the [iOS SDK documentation](/sdk/ios) and [Android SDK documentation](/sdk/android).

On iOS, you must add location usage descriptions and background modes to your `Info.plist`. Initialize the SDK in `application:didFinishLaunchingWithOptions:` in `AppDelegate.m`, passing in your Radar publishable API key:

```c
#import <RadarSDK/RadarSDK.h>
@implementation AppDelegate
-	(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
	[Radar initializeWithPublishableKey:publishableKey];  
	// ...
}
```

On Android, you must add the Google Play Services library to your project, then add the SDK to your project, preferably using Gradle. Finally, initialize the SDK in `onCreate()` in `MainActivity.java`, passing in your Radar publishable API key:

```kotlin
import io.radar.sdk.Radar;

public class MainActivity extends CordovaActivity {

  @Override
  public void onCreate() {
    super.onCreate();
    Radar.initialize(this, publishableKey);
    // ...
  }

}
```

## Integrate

### Initialize

When your app starts, initialize the SDK with your publishable key.

Use your `Test Publishable` key for testing and non-production environments. Use your `Live Publishable` key for production environments.

<Warning>
  Note that you should always use your publishable API keys, which are restricted in scope, in the SDK. Do not use your secret API keys, which are unrestricted in scope, in any client-side code.
</Warning>

```swift
cordova.plugins.radar.initialize(publishableKey);
```

### Identify user

To identify the user when logged in, call:

```swift
cordova.plugins.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:

```swift
cordova.plugins.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:

```swift
cordova.plugins.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](/sdk/ios) and [Android SDK documentation](/sdk/android).

### 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:

```javascript
cordova.plugins.radar.getPermissionsStatus((status) => {
  // do something with status
});
```

`status` will be a string, one of:

* **`GRANTED_BACKGROUND`**
* **`GRANTED_FOREGROUND`**
* **`DENIED`**
* **`UNKNOWN`**

To request location permissions for the app, call:

```javascript
cordova.plugins.radar.requestPermissions(background);
```

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](/sdk/ios) and [Android SDK documentation](/sdk/android).

### 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:

```javascript
cordova.plugins.radar.trackOnce((result) => {  // do something with result.status, result.location, result.events, result.user});
```

`status` will be a string, one of:

* **`SUCCESS`**: success
* **`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](/api#track) exceeded)
* **`ERROR_SERVER`**: internal server error
* **`ERROR_UNKNOWN`**: unknown error

Learn about platform-specific implementations of this function in the [iOS SDK documentation](/sdk/ios) and [Android SDK documentation](/sdk/android).

### Background tracking

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](/sdk/ios) and [Android SDK documentation](/sdk/android).

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

```javascript
cordova.plugins.radar.startTrackingEfficient();

cordova.plugins.radar.startTrackingResponsive();

cordova.plugins.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](/sdk/tracking).

```javascript
// optionally adjust foreground service options for android
cordova.plugins.radar.setForegroundServiceOptions({
  options: {
    text: "Location tracking started",
    title: "Location updates",
    updatesOnly: false,
    importance: 2,
    activity: 'com.yourapp.MainActivity'
  }
});

cordova.plugins.radar.startTrackingCustom({
  desiredStoppedUpdateInterval: 180,
  desiredMovingUpdateInterval: 60,
  desiredSyncInterval: 50,
  desiredAccuracy: 'high',
  stopDuration: 140,
  stopDistance: 70,
  sync: 'all',
  replay: 'none',
  showBlueBar: true,
  foregroundServiceEnabled: true
});
```

To determine whether tracking has been started, call:

```javascript
cordova.plugins.radar.isTracking();
```

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

```javascript
cordova.plugins.radar.stopTracking();
```

Learn about platform-specific implementations of these functions in the [iOS SDK documentation](/sdk/ios) and [Android SDK documentation](/sdk/android).

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

```javascript
cordova.plugins.radar.onClientLocation((location, stopped, source) => {
  // do something with location, stopped, source
});

cordova.plugins.radar.onLocation((location, user) => {
  // do something with location, user
});

cordova.plugins.radar.onEvents((events, user) => {
  // do something with events, user
});

cordova.plugins.radar.onError((err) => {
  // do something with err
});
```

<Warning>
  Listeners should be set only once and before tracking begins.
</Warning>

Add event listeners outside of your view lifecycle if you want them to work when the app is in the background.

You can also remove event listeners:

```javascript
cordova.plugins.radar.offClientLocation();

cordova.plugins.radar.offLocation();

cordova.plugins.radar.offEvents();

cordova.plugins.radar.offError();
```

### Trip tracking

On iOS and Android, to start a trip to a destination, call:

```javascript
cordova.plugins.radar.startTrip({
  externalId: '299',
  destinationGeofenceTag: 'store',
  destinationGeofenceExternalId: '123',
  mode: 'car'
}).then((result) => {
  // do something with result.status
});
cordova.plugins.radar.startTrackingContinuous();
```

Update information about the trip. Status can be set to 'unknown' to leave the status unchanged as it will update via location tracking.

```javascript
cordova.plugins.radar.updateTrip({
  status:'arrived',
  options: {
    externalId: '299',
    metadata: {
      parkingSpot: '5'
    }
  }
}).then((result) => {
  // do something with result.status
});
```

Later, to complete the trip and stop tracking, call:

```javascript
cordova.plugins.radar.completeTrip().then((result) => {
  // do something with result.status
});
cordova.plugins.radar.stopTracking();
```

Or, to cancel the trip and stop tracking, call:

```javascript
cordova.plugins.radar.cancelTrip().then((result) => {
  // do something with result.status
});
cordova.plugins.radar.stopTracking();
```

Learn more about [trip tracking](/trip-tracking).

### Manual tracking

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

```javascript
cordova.plugins.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](/sdk/ios) and [Android SDK documentation](/sdk/android).

### Other APIs

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

#### Get location

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

```javascript
cordova.plugins.radar.getLocation((result) => {
  // do something with result.status, result.location
});
```

#### Context

With the [context API](/api#context), get context for a location without sending device or user identifiers to the server:

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

#### Geocoding

With the [forward geocoding API](/api#forward-geocode), geocode an address, converting address to coordinates:

```javascript
cordova.plugins.radar.geocode('20 jay st brooklyn ny', (result) => {
  // do something with result.status, result.addresses
});
```

With the [reverse geocoding API](/api#reverse-geocode), reverse geocode a location, converting coordinates to address:

```javascript
cordova.plugins.radar.reverseGeocode({
  latitude: 40.783826,
  longitude: -73.975363
}, (result) => {
  // do something with result.status, result.addresses
});
```

With the [IP geocoding API](/api#ip-geocode), geocode the device's current IP address, converting IP address to city, state, and country:

```javascript
cordova.plugins.radar.ipGeocode((result) => {
  // do something with result.status, result.address
});
```

#### Search

With the [autocomplete API](/api#autocomplete), autocomplete partial addresses and place names, sorted by relevance:

```
cordova.plugins.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](/api#search-geofences), search for geofences near a location, sorted by distance:

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

With the [places search API](/api#search-places), search for places near a location, sorted by distance:

```
cordova.plugins.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](/api#distance), calculate the travel distance and duration from an origin to a destination:

```
cordova.plugins.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
});
```

#### Matrix

With the [matrix API](/api#matrix), calculate the travel distance and duration between multiple origins and destinations for up to 25 routes:

```
cordova.plugins.radar.getMatrix({
  origins: [
    {
      latitude: 40.78382,
      longitude: -73.97536
    }
  ],
  destinations: [
    [
      {
        latitude: 40.70390,
        longitude: -73.98670
      },
      {
        latitude: 40.73237,
        longitude: -73.94884
      }
    ]
  ],
  mode: 'car',
  units: 'imperial'
}, (result) => {
  // do something with result.status, result.matrix
});
```

## Support

Have questions? We're here to help! Contact us at [radar.com/support](https://radar.com/support).
