

# How to use Amazon Location SDK and libraries
<a name="dev-location-libraries"></a>

The Amazon Location SDK is a set of open source libraries that provide useful functionality for developing Amazon Location applications. The following functionality is included:
+ **Amazon Location client** – The Amazon Location objects in the AWS SDK v3 are bundled and packaged for ease of use in web development.
+ **Authentication** – The authentication utility simplifies the authentication (using Amazon Cognito or API keys) when building a web page, [JavaScript](https://docs.aws.amazon.com//location/previous/developerguide/dev-location-libraries.html#loc-sdk-auth), [iOS](https://docs.aws.amazon.com//location/previous/developerguide/dev-location-libraries.html#loc-sdk-auth-mobile-ios), or [Android](https://docs.aws.amazon.com//location/previous/developerguide/dev-location-libraries.html#loc-sdk-auth-mobile-Android) application for Amazon Location Service.
+ **Tracking** – The mobile tracking SDKs are available for [iOS](https://docs.aws.amazon.com//location/previous/developerguide/dev-location-libraries.html#loc-mobile-tracking-ios) and [Android](https://docs.aws.amazon.com//location/previous/developerguide/dev-location-libraries.html#loc-mobile-tracking-android). This SDK makes it easier for mobile applications to interact with Amazon Location Trackers.
+ **Amazon Location GeoJSON functions** – The [GeoJSON conversion utilities](https://docs.aws.amazon.com//location/previous/developerguide/dev-location-libraries.html#loc-sdk-geojson) make it easy to convert between the industry-standard [GeoJSON](https://geojson.org/) formatted data, and the Amazon Location API formats.

The Amazon Location SDK is a set of functions that can make using the Amazon Location Service in an application simpler. You can install and import these functions into your JavaScript application. The following sections describe the Amazon Location client, and the authentication and GeoJSON helper libraries.

**Topics**
+ [Amazon Location client](loc-sdk-client.md)
+ [JavaScript Authentication helper](loc-sdk-auth.md)
+ [GeoJSON conversion helpers](loc-sdk-geojson.md)
+ [Android Mobile Authentication SDK](loc-sdk-auth-mobile-Android.md)
+ [iOS Mobile Authentication SDK](loc-sdk-auth-mobile-ios.md)
+ [Android Mobile Tracking SDK](loc-mobile-tracking-android.md)
+ [iOS Mobile Tracking SDK](loc-mobile-tracking-ios.md)

# Amazon Location client
<a name="loc-sdk-client"></a>

With AWS SDK v3, the SDK is separated out by service. You can install just the parts that you need. For example, to install the Amazon Location client and the credentials provider for Amazon Cognito, use the following commands.

```
npm install @aws-sdk/client-location
npm install @aws-sdk/credential-providers
```

In order to facilitate using Amazon Location Service in JavaScript web frontend applications, AWS provides a hosted bundle of the Amazon Location library and the credentials provider. To use the bundled client, add it to your HTML in a script tag, as follows:

```
<script src="https://unpkg.com/@aws/amazon-location-client@1.x/dist/amazonLocationClient.js"></script>
```

**Note**  
The package is kept up to date and backward compatible for ease of use. Using this script tag or NPM install will always get the latest version.

# JavaScript Authentication helper
<a name="loc-sdk-auth"></a>

The Amazon Location JavaScript authentication helper makes it simpler to authenticate when making Amazon Location API calls from your JavaScript application. This authentication helper specifically help you when using [Amazon Cognito](authenticating-using-cognito.md) or [API keys](using-apikeys.md) as your authentication method. This is an open source library that is available on GitHub, here: [https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js](https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js). 

**Note**  
The Amazon Cognito support in the authentication helper does not support the federated identities feature of Amazon Cognito.

**Installation**

You can use the libraries with a local install, if you use a build system like webpack, or by including pre-built JavaScript bundles with `<script>` tags in your html.
+ Use the following command to install the library, using NPM:

  ```
  npm install @aws/amazon-location-utilities-auth-helper
  ```
+ Use the following command in your HTML file to load the script:

  ```
  <script src="https://unpkg.com/@aws/amazon-location-utilities-auth-helper@1.x/dist/amazonLocationAuthHelper.js"></script>
  ```

**Import**

To use a specific function in your JavaScript application, you must import that function. The following code is used to import the function `withIdentityPoolId` into your application.

```
import { withIdentityPoolId } from '@aws/amazon-location-utilities-auth-helper';
```

## Authentication functions
<a name="loc-sdk-auth-functions"></a>

The Amazon Location authentication helpers include the following functions that return an `AuthHelper` object:
+ `async withIdentityPoolId( identityPoolId: string): AuthHelper` – This function returns an AuthHelper object, initialized to work with Amazon Cognito
+ `async withAPIKey( API_KEY: string): AuthHelper` – This function returns an AuthHelper object, initialized to work with API Keys.

The `AuthHelper` object provides the following functions:
+ `AuthHelper.getMapAuthenticationOptions()` – This function of the AuthHelper object returns a JavaScript object with the `transformRequest` that can be used with the map options in MapLibre JS. Only provided when initialized with an identity pool.
+ `AuthHelper.getLocationClientConfig()` – This function of the AuthHelper object returns a JavaScript object with the `credentials` that can be used to initialize a LocationClient.
+ `AuthHelper.getCredentials()` – This function of the AuthHelper object returns the internal credentials from Amazon Cognito. Only provided when initialized with an identity pool.

**Example: Initializing MapLibre map object with Amazon Cognito, using an AuthHelper**

```
import { withIdentityPoolId } from '@aws/amazon-location-utilities-auth-helper';

const authHelper = await withIdentityPoolId("identity-pool-id"); // use Cognito pool id for credentials

const map = new maplibregl.Map({
    container: "map", // HTML element ID of map element
    center: [-123.1187, 49.2819], // initial map center point
    zoom: 16, // initial map zoom
    style: https://maps.geo.region.amazonaws.com/maps/v0/maps/mapName/style-descriptor', // Defines the appearance of the map
    ...authHelper.getMapAuthenticationOptions(), // Provides credential options required for requests to Amazon Location
});
```

**Example: Initializing MapLibre map object with an API key (`AuthHelper` is not needed in this case)**

```
const map = new maplibregl.Map({
    container: "map", // HTML element ID of map element
    center: [-123.1187, 49.2819], // initial map center point
    zoom: 16, // initial map zoom
    style: https://maps.geo.region.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor?key=api-key-id',
});
```

**Example: Initialize the Location client from the AWS SDK for JS, using Amazon Cognito and AuthHelper**

This example uses AWS SDK for JavaScript v3.

```
import { withIdentityPoolId } from '@aws/amazon-location-utilities-auth-helper';

const authHelper = await withIdentityPoolId("identity-pool-id"); // use Cognito pool id for credentials

//initialize the Location client:
const client = new LocationClient({
    region: "region",
    ...authHelper.getLocationClientConfig() // sets up the Location client to use the Cognito pool defined above
});

//call a search function with the location client:
const result = await client.send(new SearchPlaceIndexForPositionCommand({
    IndexName: "place-index", // Place index resource to use
    Position: [-123.1187, 49.2819], // position to search near
    MaxResults: 10 // number of results to return
});
```

**Example: Initialize the Location client from the AWS SDK for JS, using an API key and AuthHelper**

This example uses AWS SDK for JavaScript v3.

```
import { withAPIKey } from '@aws/amazon-location-utilities-auth-helper';

const authHelper = await withAPIKey("api-key-id"); // use API Key id for credentials

//initialize the Location client:
const client = new LocationClient({
    region: "region",
    ...authHelper.getLocationClientConfig() // sets up the Location client to use the API Key defined above
});

//call a search function with the location client:
const result = await client.send(new SearchPlaceIndexForPositionCommand({
    IndexName: "place-index", // Place index resource to use
    Position: [-123.1187, 49.2819], // position to search near
    MaxResults: 10 // number of results to return
});
```

# GeoJSON conversion helpers
<a name="loc-sdk-geojson"></a>

The Amazon Location GeoJSON conversion helpers provide tools to convert Amazon Location Service data types to and from the industry-standard [GeoJSON](https://geojson.org/) format. GeoJSON is used, for example, with MapLibre to render geographic data on the map. This is an open source library that is available on GitHub, here: [https://github.com/aws-geospatial/amazon-location-utilities-datatypes-js](https://github.com/aws-geospatial/amazon-location-utilities-datatypes-js). 

**Installation**

You can use the libraries with a local install, like webpack, or by including pre-built JavaScript bundles with `<script>` tags in your html.
+ Use the following command to install the library, using NPM.

  ```
  npm install @aws/amazon-location-utilities-datatypes
  ```
+ Use the following command in your HTML file to load the script:

  ```
  <script src="https://unpkg.com/@aws/amazon-location-utilities-datatypes@1.x/dist/amazonLocationDataConverter.js"></script>
  ```

**Import**

To use a specific function in your JavaScript application, you must import that function. The following code is used to import the function `placeToFeatureCollection` into your application.

```
import { placeToFeatureCollection } from '@aws/amazon-location-utilities-datatypes';
```

## GeoJSON conversion functions
<a name="loc-sdk-geojson-functions"></a>

The Amazon Location GeoJSON conversion helpers include the following functions:
+ `placeToFeatureCollection(place: GetPlaceResponse | searchPlaceIndexForPositionResponse | searchPlaceIndexForTextResponse, keepNull: boolean): Feature` – This function converts responses from the place search functions to a GeoJSON FeatureCollection with 1 or more Point features.
+ `devicePositionToFeatureCollection(devicePositions: GetDevicePositionResponse | BatchGetDevicePositionResponse | GetDevicePositionHistoryResponse | ListDevicePositionsResponse, keepNull: boolean)` – This function converts responses from the tracker device position functions to a GeoJSON FeatureCollection with 1 or more Point features.
+ `routeToFeatureCollection(legs: CalculateRouteResponse): FeatureCollection` – This function converts responses from the calculate route function to a GeoJSON FeatureCollection with a single MultiStringLine feature. Each leg of the route is represented by a LineString entry in the MultiStringLine.
+ `geofenceToFeatureCollection(geofences: GetGeofenceResponse | PutGeofenceRequest | BatchPutGeofenceRequest | ListGeofencesResponse): FeatureCollection` – This function converts geofence functions request or response to a GeoJSON FeatureCollection with Polygon features. It can convert geofences both in the response and the request, allowing you to show geofences on a map before uploading them with PutGeofence or BatchPutGeofence.

  This function will convert a circle geofence to a feature with an approximated polygon, but will also have "center" and "radius" properties to recreate the circle geofence, if necessary (see the next function).
+ `featureCollectionToGeofences(featureCollection: FeatureCollection): BatchPutGeofenceRequestEntry[]` – This function converts a GeoJSON FeatureCollection with Polygon features to an array of BatchPutGeofenceRequestEntry objects, so the result can be used to create a request to BatchPutGeofence.

  If a Feature in the FeatureCollection has "center" and "radius" properties, it will be converted into a circle geofence request entry, ignoring the geometry of the polygon.

**Example: Convert search results to a point layer in MapLibre**

This example uses AWS SDK for JavaScript v3.

```
import { placeToFeatureCollection } from '@aws/amazon-location-utility-datatypes';

...

let map; // map here is an initialized MapLibre instance

const client = new LocationClient(config);
const input = { your_input };
const command = new searchPlaceIndexForTextCommand(input);
const response = await client.send(command);

// calling utility function to convert the response to GeoJSON
const featureCollection = placeToFeatureCollection(response);
map.addSource("search-result", featureCollection);
map.addLayer({
    id: "search-result",
    type: "circle",
    source: "search-result",
    paint: {
        "circle-radius": 6,
        "circle-color": "#B42222",
    },
});
```

# Android Mobile Authentication SDK
<a name="loc-sdk-auth-mobile-Android"></a>

These utilities help you authenticate when making Amazon Location Service API calls from your Android applications. This specifically helps when using [Amazon Cognito](https://docs.aws.amazon.com//location/previous/developerguide/authenticating-using-cognito.html) or [API keys](https://docs.aws.amazon.com/location/previous/developerguide/using-apikeys.html) as the authentication method.

The Android mobile authentication SDK is available on github: [Amazon Location Service Mobile Authentication SDK for Android](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-android/tree/main). Additionally, both the mobile authentication SDK and the AWS SDK are available on the [AWS Maven repository](https://central.sonatype.com/artifact/software.amazon.location/tracking).

## Installation
<a name="loc-sdk-auth-mobile-Android-install"></a>

To use the mobile authentication SDK, add the following import statements to your `build.gradle` file in Android Studio. 

```
implementation("software.amazon.location:auth:0.0.1")
implementation("com.amazonaws:aws-android-sdk-location:2.72.0")
```

## Authentication Functions
<a name="loc-sdk-auth-mobile-Android-functions"></a>

The authentication helper SDK has the following functions:
+ `authHelper.authenticateWithApiKey("My-Amazon-Location-API-Key"): LocationCredentialsProvider`: This function returns a `LocationCredentialsProvider` initialized to work with an API Key. 
+ `authHelper.authenticateWithCognitoIdentityPool("My-Cognito-Identity-Pool-Id"): LocationCredentialsProvider`: This function returns a `LocationCredentialsProvider` initialized to work with an Amazon Cognito identity pool. 

## Usage
<a name="loc-sdk-auth-mobile-Android-usage"></a>

To use the SDK in your code, import the following classes:

```
import com.amazonaws.services.geo.AmazonLocationClient
import software.amazon.location.auth.AuthHelper
import software.amazon.location.auth.LocationCredentialsProvider
```

You have two options when creating the authentication helper and location client provider instances. You can create an instance using [Amazon Location API keys](https://docs.aws.amazon.com//location/previous/developerguide/using-apikeys.html) or [Amazon Cognito](https://docs.aws.amazon.com//location/previous/developerguide/using-apikeys.html).
+ To create an authentication helper instance using an Amazon Location API Key, declare the helper class as follows:

  ```
  var authHelper = AuthHelper(applicationContext)
  var locationCredentialsProvider : LocationCredentialsProvider = authHelper.authenticateWithApiKey("My-Amazon-Location-API-Key")
  ```
+ To create an authentication helper instance using Amazon Cognito, declare the helper class as follows:

  ```
  var authHelper = AuthHelper(applicationContext)
  var locationCredentialsProvider : LocationCredentialsProvider = authHelper.authenticateWithCognitoIdentityPool("My-Cognito-Identity-Pool-Id")
  ```

You can create an Amazon Location client instance using the location credentials provider and make calls to the Amazon Location service. The following example searches for places near a specified latitude and longitude.

```
var locationClient = authHelper.getLocationClient(locationCredentialsProvider.getCredentialsProvider())
var searchPlaceIndexForPositionRequest = SearchPlaceIndexForPositionRequest().withIndexName("My-Place-Index-Name").withPosition(arrayListOf(30.405423, -97.718833))
var nearbyPlaces = locationClient.searchPlaceIndexForPosition(searchPlaceIndexForPositionRequest)
```

# iOS Mobile Authentication SDK
<a name="loc-sdk-auth-mobile-ios"></a>

These utilities help you authenticate when making Amazon Location Service API calls from your iOS applications. This specifically helps when using [Amazon Cognito](https://docs.aws.amazon.com//location/previous/developerguide/authenticating-using-cognito.html) or [API keys](https://docs.aws.amazon.com/location/previous/developerguide/using-apikeys.html) as the authentication method.

The iOS mobile authentication SDK is available on github: [Amazon Location Service Mobile Authentication SDK for iOS](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/tree/main).

## Installation
<a name="loc-sdk-auth-mobile-Android-install"></a>

Install the SDK in an Xcode project:

1. Go to **File**, then select **Add Package Dependencies** in your XCode project.

1. Type the package URL: [https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/) into the search bar and press the enter key.

1. Select the `amazon-location-mobile-auth-sdk-ios` package and press **Add Package**.

1. Select the `AmazonLocationiOSAuthSDK` package product and press **Add Package**.

## Authentication Functions
<a name="loc-sdk-auth-mobile-ios-functions"></a>

The authentication helper SDK has the following functions:
+ `authHelper.authenticateWithApiKey("My-Amazon-Location-API-Key"): LocationCredentialsProvider`: This function returns a `LocationCredentialsProvider` initialized to work with an API Key. 
+ `authHelper.authenticateWithCognitoIdentityPool("My-Cognito-Identity-Pool-Id"): LocationCredentialsProvider`: This function returns a `LocationCredentialsProvider` initialized to work with an Amazon Cognito identity pool. 

## Usage
<a name="loc-sdk-auth-mobile-ios-usage"></a>

To use the mobile authentication SDK, add the following statements to your activity:

```
import AmazonLocationiOSAuthSDK
import AWSLocationXCF
```

You have two options when creating the authentication helper and location client provider instances. You can create an instance using [Amazon Location API keys](https://docs.aws.amazon.com//location/previous/developerguide/using-apikeys.html) or [Amazon Cognito](https://docs.aws.amazon.com//location/previous/developerguide/using-apikeys.html).
+ To create an authentication helper instance using an Amazon Location API Key, declare the helper class as follows:

  ```
  let authHelper = AuthHelper()
  let locationCredentialsProvider = authHelper.authenticateWithAPIKey(apiKey: "My-Amazon-Location-API-Key", region: "account-region")
  ```
+ To create an authentication helper instance using Amazon Cognito, declare the helper class as follows:

  ```
  let authHelper = AuthHelper()
  let locationCredentialsProvider = authHelper.authenticateWithCognitoUserPool(identityPoolId: "My-Amazon-Location-API-Key", region: "account-region")
  ```

You can create an Amazon Location client instance using the location credentials provider and make calls to the Amazon Location service. The following example searches for places near a specified latitude and longitude.

```
let locationClient = AWSLocation.default()
let searchPlaceIndexForPositionRequest = AWSLocationSearchPlaceIndexForPositionRequest()!
searchPlaceIndexForPositionRequest.indexName = "My-Place-Index-Name"
searchPlaceIndexForPositionRequest.position = [30.405423, -97.718833]
let nearbyPlaces = locationClient.searchPlaceIndex(forPosition: searchPlaceIndexForPositionRequest)
```

# Android Mobile Tracking SDK
<a name="loc-mobile-tracking-android"></a>

The Amazon Location mobile tracking SDK provides utilities which help easily authenticate, capture device positions, and send position updates to Amazon Location Trackers. The SDK supports local filtering of location updates with configurable update intervals. This reduces data costs and optimizes intermittent connectivity for your Android applications.

The Android tracking SDK is available on GitHub: [Amazon Location Mobile Tracking SDK for Android](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-android). Additionally, both the mobile authentication SDK and the AWS SDK are available on the [AWS Maven repository](https://central.sonatype.com/artifact/software.amazon.location/tracking). The Android tracking SDK is designed to work with the general AWS SDK.

This section covers the following topics for the Amazon Location mobile tracking Android SDK:

**Topics**
+ [Installation](#loc-mobile-tracking-install-android)
+ [Usage](#loc-mobile-tracking-usage-android)
+ [Filters](#loc-mobile-tracking-android-filters)
+ [Android Mobile SDK tracking functions](#loc-mobile-tracking-functions)
+ [Examples](#loc-mobile-tracking-example-android)

## Installation
<a name="loc-mobile-tracking-install-android"></a>

To install the SDK, add the following lines to the dependencies section of your build.gradle file in Android Studio:

```
implementation("software.amazon.location:tracking:0.0.1")
implementation("software.amazon.location:auth:0.0.1")
implementation("com.amazonaws:aws-android-sdk-location:2.72.0")
```

## Usage
<a name="loc-mobile-tracking-usage-android"></a>

This procedure shows you how to use the SDK to authenticate and create the `LocationTracker` object:

**Note**  
This procedure assumes you have imported the library mentioned in the [Installation](#loc-mobile-tracking-install-android) section.

1. Import the following classes in your code:

   ```
   import software.amazon.location.tracking.LocationTracker
   import software.amazon.location.tracking.config.LocationTrackerConfig
   import software.amazon.location.tracking.util.TrackingSdkLogLevel
   import com.amazonaws.services.geo.AmazonLocationClient
   import software.amazon.location.auth.AuthHelper
   import software.amazon.location.auth.LocationCredentialsProvider
   ```

1. Next create an `AuthHelper`, since the `LocationCredentialsProvider` parameter is required for creating a `LocationTracker` object:

   ```
   // Create an authentication helper using credentials from Cognito
   val authHelper = AuthHelper(applicationContext)
   val locationCredentialsProvider : LocationCredentialsProvider = authHelper.authenticateWithCognitoIdentityPool("My-Cognito-Identity-Pool-Id")
   ```

1. Now, use the `LocationCredentialsProvider` and `LocationTrackerConfig` to create a `LocationTracker` object:

   ```
   val config = LocationTrackerConfig(
       trackerName = "MY-TRACKER-NAME",
       logLevel = TrackingSdkLogLevel.DEBUG,
       accuracy = Priority.PRIORITY_HIGH_ACCURACY,
       latency = 1000,
       frequency = 5000,
       waitForAccurateLocation = false,
       minUpdateIntervalMillis = 5000,
   )
   locationTracker = LocationTracker(
       applicationContext,
       locationCredentialsProvider,
       config,
   )
   ```

## Filters
<a name="loc-mobile-tracking-android-filters"></a>

The Amazon Location mobile tracking Android SDK has three inbuilt location filters.
+ `TimeLocationFilter`: Filters the current location to be uploaded based on a defined time interval.
+ `DistanceLocationFilter`: Filters location updates based on a specified distance threshold.
+ `AccuracyLocationFilter`: Filters location updates by comparing the distance moved since the last update with the current location's accuracy.

This example adds filters in the `LocationTracker` at the creation time:

```
val config = LocationTrackerConfig(
    trackerName = "MY-TRACKER-NAME",
    logLevel = TrackingSdkLogLevel.DEBUG,
    accuracy = Priority.PRIORITY_HIGH_ACCURACY,
    latency = 1000,
    frequency = 5000,
    waitForAccurateLocation = false,
    minUpdateIntervalMillis = 5000,
    locationFilters = mutableListOf(TimeLocationFilter(), DistanceLocationFilter(), AccuracyLocationFilter())
)
locationTracker = LocationTracker(
    applicationContext,
    locationCredentialsProvider,
    config,
)
```

This example enables and disables filter at runtime with `LocationTracker`:

```
// To enable the filter
locationTracker?.enableFilter(TimeLocationFilter())

// To disable the filter
locationTracker?.disableFilter(TimeLocationFilter())
```

## Android Mobile SDK tracking functions
<a name="loc-mobile-tracking-functions"></a>

The Amazon Location mobile tracking SDK for Android includes the following functions:
+ **Class**: `LocationTracker`

  `constructor(context: Context,locationCredentialsProvider: LocationCredentialsProvider,trackerName: String)`, or `constructor(context: Context,locationCredentialsProvider: LocationCredentialsProvider,clientConfig: LocationTrackerConfig)`

  This is an initializer function to create a `LocationTracker` object. It requires instances of `LocationCredentialsProvider` , `trackerName` and optionally an instance of `LocationTrackingConfig`. If the config is not provided it will be initialized with default values.
+ **Class**: `LocationTracker`

  `start(locationTrackingCallback: LocationTrackingCallback)`

  Starts the process of accessing the user's location and sending it to an Amazon Location tracker.
+ **Class**: `LocationTracker`

  `isTrackingInForeground()`

  Checks if location tracking is currently in progress.
+ **Class**: `LocationTracker`

  `stop()`

  Stops the process of tracking the user's location.
+ **Class**: `LocationTracker`

  `startTracking()`

  Starts the process of accessing the user's location and sending it to the AWS tracker.
+ **Class**: `LocationTracker`

  `startBackground(mode: BackgroundTrackingMode, serviceCallback: ServiceCallback)`

  Starts the process of accessing the user's location and sending it to the AWS tracker while the application is in the background. BackgroundTrackingMode has the following options:
  + `ACTIVE_TRACKING`: This option actively tracks a user's location updates. 
  + `BATTERY_SAVER_TRACKING`: This option tracks user's location updates every 15 minutes.
+ **Class**: `LocationTracker`

  `stopBackgroundService()`

  Stops the process of accessing the user's location and sending it to the AWS tracker while the application is in the background.
+ **Class**: `LocationTracker`

  `getTrackerDeviceLocation()`

  Retrieves the device location from Amazon Location services. 
+ **Class**: `LocationTracker`

  `getDeviceLocation(locationTrackingCallback: LocationTrackingCallback?)`

  Retrieves the current device location from the fused location provider client and uploads it to Amazon Location tracker.
+ **Class**: `LocationTracker`

  `uploadLocationUpdates(locationTrackingCallback: LocationTrackingCallback?)`

  Uploads the device location to Amazon Location services after filtering based on the configured location filters.
+ **Class**: `LocationTracker`

  `enableFilter(filter: LocationFilter)`

  Enables a particular location filter.
+ **Class**: `LocationTracker`

  `checkFilterIsExistsAndUpdateValue(filter: LocationFilter)`

  Disable particular location filter.
+ **Class**: `LocationTrackerConfig`

  `LocationTrackerConfig( // Required var trackerName: String, // Optional var locationFilters: MutableList = mutableListOf( TimeLocationFilter(), DistanceLocationFilter(), ), var logLevel: TrackingSdkLogLevel = TrackingSdkLogLevel.DEBUG, var accuracy: Int = Priority.PRIORITY_HIGH_ACCURACY, var latency: Long = 1000, var frequency: Long = 1500, var waitForAccurateLocation: Boolean = false, var minUpdateIntervalMillis: Long = 1000, var persistentNotificationConfig: NotificationConfig = NotificationConfig()) `

  This initializes the `LocationTrackerConfig` with user-defined parameter values. If a parameter value is not provided, it will be set to a default value.
+ **Class**: `LocationFilter`

  `shouldUpload(currentLocation: LocationEntry, previousLocation: LocationEntry?): Boolean`

  The `LocationFilter` is a protocol that users can implement for their custom filter implementation. You need to implement the `shouldUpload` function to compare previous and current location and return if the current location should be uploaded.

## Examples
<a name="loc-mobile-tracking-example-android"></a>

The following code sample shows the mobile tracking SDK functionality.

This example uses the `LocationTracker` to start and stop tracking in background:

```
// For starting the location tracking
locationTracker?.startBackground(
BackgroundTrackingMode.ACTIVE_TRACKING,
object : ServiceCallback {
    override fun serviceStopped() {
        if (selectedTrackingMode == BackgroundTrackingMode.ACTIVE_TRACKING) {
            isLocationTrackingBackgroundActive = false
        } else {
            isLocationTrackingBatteryOptimizeActive = false
        }
    }
},
)

// For stopping the location tracking
locationTracker?.stopBackgroundService()
```

# iOS Mobile Tracking SDK
<a name="loc-mobile-tracking-ios"></a>

The Amazon Location mobile tracking SDK provides utilities which help easily authenticate, capture device positions, and send position updates to Amazon Location Trackers. The SDK supports local filtering of location updates with configurable update intervals. This reduces data costs and optimizes intermittent connectivity for your iOS applications.

The iOS tracking SDK is available on GitHub: [Amazon Location Mobile Tracking SDK for iOS](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios).

This section covers the following topics for the Amazon Location mobile tracking iOS SDK:

**Topics**
+ [Installation](#loc-mobile-tracking-install-ios)
+ [Usage](#loc-mobile-tracking-usage-ios)
+ [Filters](#loc-mobile-tracking-ios-filters)
+ [iOS Mobile SDK tracking functions](#loc-mobile-tracking-functions)
+ [Examples](#loc-mobile-tracking-example-ios)

## Installation
<a name="loc-mobile-tracking-install-ios"></a>

Use the following procedure to install the mobile tracking SDK for iOS:

1. In your Xcode project, go to **File** and select **Add Package Dependencies**.

1. Type the following URL: [https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios/](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios/) into the search bar and press the enter key.

1. Select the `amazon-location-mobile-tracking-sdk-ios` package and click on **Add Package**.

1. Select the `AmazonLocationiOSTrackingSDK` package product and click on **Add Package**.

## Usage
<a name="loc-mobile-tracking-usage-ios"></a>

The following procedure shows you how to create an authentication helper using credentials from Cognito.

1. After installing the library, you need to add one or both of the descriptions into your `info.plist` file:

   ```
   Privacy - Location When In Use Usage Description
   Privacy - Location Always and When In Use Usage Description
   ```

1. Next, import the AuthHelper in your class:

   ```
   import AmazonLocationiOSAuthSDKimport AmazonLocationiOSTrackingSDK
   ```

1. Then you will create an `AuthHelper` object and use it with the AWS SDK, by creating an authentication helper using credentials from Amazon Cognito.

   ```
   let authHelper = AuthHelper()
   let locationCredentialsProvider = authHelper.authenticateWithCognitoUserPool(identityPoolId: "My-Cognito-Identity-Pool-Id", region: "My-region") //example: us-east-1
   let locationTracker = LocationTracker(provider: locationCredentialsProvider, trackerName: "My-tracker-name")
   
   // Optionally you can set ClientConfig with your own values in either initialize or in a separate function
   // let trackerConfig = LocationTrackerConfig(locationFilters: [TimeLocationFilter(), DistanceLocationFilter()],
   
   trackingDistanceInterval: 30,
   trackingTimeInterval: 30,
   logLevel: .debug)
   
   // locationTracker = LocationTracker(provider: credentialsProvider, trackerName: "My-tracker-name",config: trackerConfig)
   // locationTracker.setConfig(config: trackerConfig)
   ```

## Filters
<a name="loc-mobile-tracking-ios-filters"></a>

The Amazon Location mobile tracking iOS SDK has three inbuilt location filters.
+ `TimeLocationFilter`: Filters the current location to be uploaded based on a defined time interval.
+ `DistanceLocationFilter`: Filters location updates based on a specified distance threshold.
+ `AccuracyLocationFilter`: Filters location updates by comparing the distance moved since the last update with the current location's accuracy.

This example adds filters in the `LocationTracker` at the creation time:

```
val config = LocationTrackerConfig(
    trackerName = "MY-TRACKER-NAME",
    logLevel = TrackingSdkLogLevel.DEBUG,
    accuracy = Priority.PRIORITY_HIGH_ACCURACY,
    latency = 1000,
    frequency = 5000,
    waitForAccurateLocation = false,
    minUpdateIntervalMillis = 5000,
    locationFilters = mutableListOf(TimeLocationFilter(), DistanceLocationFilter(), AccuracyLocationFilter())
)

locationTracker = LocationTracker(
    applicationContext,
    locationCredentialsProvider,
    config,
)
```

This example enables and disables filter at runtime with `LocationTracker`:

```
// To enable the filter
locationTracker?.enableFilter(TimeLocationFilter())

// To disable the filter
locationTracker?.disableFilter(TimeLocationFilter())
```

## iOS Mobile SDK tracking functions
<a name="loc-mobile-tracking-functions"></a>

The Amazon Location mobile tracking SDK for iOS includes the following functions:
+ **Class**: `LocationTracker`

  `init(provider: LocationCredentialsProvider, trackerName: String, config: LocationTrackerConfig? = nil)`

  This is an initializer function to create a `LocationTracker` object. It requires instances of `LocationCredentialsProvider` , `trackerName` and optionally an instance of `LocationTrackingConfig`. If the config is not provided it will be initialized with default values.
+ **Class**: `LocationTracker`

  `setTrackerConfig(config: LocationTrackerConfig)`

  This sets Tracker's config to take effect at any point after initialization of location tracker
+ **Class**: `LocationTracker`

  `getTrackerConfig()`

  This gets the location tracking config to use or modify in your app.

  Returns: `LocationTrackerConfig`
+ **Class**: `LocationTracker`

  `getDeviceId()`

  Gets the location tracker's generated device Id.

  Returns: `String?`
+ **Class**: `LocationTracker`

  `startTracking()`

  Starts the process of accessing the user's location and sending it to the AWS tracker.
+ **Class**: `LocationTracker`

  `resumeTracking()`

  Resumes the process of accessing the user's location and sending it to the AWS tracker.
+ **Class**: `LocationTracker`

  `stopTracking()`

  Stops the process of tracking the user's location.
+ **Class**: `LocationTracker`

  `startBackgroundTracking(mode: BackgroundTrackingMode)`

  Starts the process of accessing the user's location and sending it to the AWS tracker while the application is in the background. `BackgroundTrackingMode` has the following options: 
  + `Active:` This option doesn't automatically pauses location updates.
  + `BatterySaving:` This option automatically pauses location updates
  + `None:` This option overall disables background location updates
+ **Class**: `LocationTracker`

  `resumeBackgroundTracking(mode: BackgroundTrackingMode)`

  Resumes the process of accessing the user's location and sending it to the AWS tracker while the application is in the background.
+ **Class**: `LocationTracker`

  `stopBackgroundTracking()`

  Stops the process of accessing the user's location and sending it to the AWS tracker while the application is in the background.
+ **Class**: `LocationTracker`

  `getTrackerDeviceLocation(nextToken: String?, startTime: Date? = nil, endTime: Date? = nil, completion: @escaping (Result<GetLocationResponse, Error>)`

  Retrieves the uploaded tracking locations for the user's device between start and end date and time.

  Returns: `Void`
+ **Class**: `LocationTrackerConfig`

  `init()`

  This initializes the LocationTrackerConfig with default values.
+ **Class**: `LocationTrackerConfig`

  `init(locationFilters: [LocationFilter]? = nil, trackingDistanceInterval: Double? = nil, trackingTimeInterval: Double? = nil, trackingAccuracyLevel: Double? = nil, uploadFrequency: Double? = nil, desiredAccuracy: CLLocationAccuracy? = nil, activityType: CLActivityType? = nil, logLevel: LogLevel? = nil)`

  This initializes the `LocationTrackerConfig` with user-defined parameter values. If a parameter value is not provided it will be set to a default value.
+ **Class**: `LocationFilter`

  `shouldUpload(currentLocation: LocationEntity, previousLocation: LocationEntity?, trackerConfig: LocationTrackerConfig)`

  The `LocationFilter` is a protocol that users can implement for their custom filter implementation. A user would need to implement `shouldUpload` function to compare previous and current location and return if the current location should be uploaded.

## Examples
<a name="loc-mobile-tracking-example-ios"></a>

This sections details examples of using the Amazon Location Mobile Tracking SDK for iOS.

**Note**  
Ensure that the necessary permissions are set in the `info.plist` file. These are the same permissions listed in the [Usage](#loc-mobile-tracking-usage-ios) section.

The following example demonstrates functionality for tracking device location and retrieving tracked locations:

```
Privacy - Location When In Use Usage Description
Privacy - Location Always and When In Use Usage Description
```

Start tracking the location:

```
do {
    try locationTracker.startTracking()
    } 
catch TrackingLocationError.permissionDenied {
        // Handle permissionDenied by showing the alert message or opening the app settings
        }
```

Resume tracking the location:

```
do { 
    try locationTracker.resumeTracking()
    } 
catch TrackingLocationError.permissionDenied {
    // Handle permissionDenied by showing the alert message or opening the app settings
    }
```

Stop tracking the location:

```
locationTracker.stopTracking()
```

Start background tracking:

```
do {
    locationTracker.startBackgroundTracking(mode: .Active) // .Active, .BatterySaving, .None
    } 
catch TrackingLocationError.permissionDenied {
   // Handle permissionDenied by showing the alert message or opening the app settings
   }
```

Resume background tracking:

```
do {
    locationTracker.resumeBackgroundTracking(mode: .Active)
    } 
catch TrackingLocationError.permissionDenied {
    // Handle permissionDenied by showing the alert message or opening the app settings
    }
```

To stop background tracking:

```
locationTracker.stopBackgroundTracking()
```

Retrieve device's tracked locations from the tracker:

```
func getTrackingPoints(nextToken: String? = nil) {
let startTime: Date = Date().addingTimeInterval(-86400) // Yesterday's day date and time
let endTime: Date = Date() 
locationTracker.getTrackerDeviceLocation(nextToken: nextToken, startTime: startTime, endTime: endTime, completion: { [weak self] result in
    switch result {
    case .success(let response):
        
        let positions = response.devicePositions
        // You can draw positions on map or use it further as per your requirement

        // If nextToken is available, recursively call to get more data
        if let nextToken = response.nextToken {
            self?.getTrackingPoints(nextToken: nextToken)
        }
    case .failure(let error):
        print(error)
    }
})
}
```