

# Geofencing an area of interest using Amazon Location
Geofencing and tracking

A geofencing application evaluates a tracked device’s position relative to previously registered areas of interest. This enables actions to be taken based on position updates. For example, you can initiate an event that prompts a notification when a customer who ordered coffee on their mobile app is near a store.

**Note**  
For an overview of geofencing and tracker concepts, see [Learn about geofences and trackers in Amazon Location Service](geofence-tracker-concepts.md).

This section of the guide provides step-by-step instructions for creating a geofencing application using Amazon Location Service.

Overview of steps

1. Add geofences around areas of interest and store them in a geofence collection resource. 

1. Start tracking your target devices and store the device location history in a tracker resource.

1. Link your tracker resource to your geofence collection resource so that device location updates are automatically evaluated against all your geofences.

1. You can evaluate device positions directly against your geofence collection resources if you don’t want to use Amazon Location Trackers to keep your devices’ location history.

After you implement your geofencing solution, your geofence collection resource emits the following events:
+ `ENTER` — A tracked device enters a geofence within a geofence collection.
+ `EXIT` — A tracked device exits a geofence within a geofence collection.

You can use Amazon EventBridge to react to events by routing them elsewhere.

As an alternative to sending updates via the Amazon Location Service APIs from each device, you can use MQTT to send device updates.

The following topics describe these steps and alternatives in detail.

**Topics**
+ [

# Add geofences with Amazon Location
](add-geofences.md)
+ [

# Start tracking with Amazon Location
](start-tracking.md)
+ [

# Tutorial: Link a tracker to a geofence collection in Amazon Location
](associate-consumer.md)
+ [

# Evaluate device positions against geofences in Amazon Location
](evaluate-geofences.md)
+ [

# Tutorial: Verify device positions with Amazon Location
](verify-device-positions.md)
+ [

# Reacting to Amazon Location Service events with Amazon EventBridge
](location-events.md)
+ [

# Track with AWS IoT, MQTT, with Amazon Location Service
](tracking-using-mqtt.md)
+ [

# Manage geofence collection resources with Amazon Location
](managing-geofence-collections.md)
+ [

# Manage tracker resources with Amazon Location
](managing-trackers.md)
+ [

# Sample Geofencing and Tracking mobile application
](geofence-tracking-tutorials.md)

# Add geofences with Amazon Location
Add geofences

Geofences contain points and vertices that form a closed boundary, which defines an area of interest. Geofence collections store and manage one or multiple geofences. 

Amazon Location geofence collections stores geofences defined by using a standard geospatial data format called [GeoJSON (RFC 7946)](https://geojson.org/). You can use tools, such as [geojson.io](http://geojson.io/), at no charge to draw your geofences graphically and save the output GeoJSON file.

**Note**  
Amazon Location doesn't support polygons with holes, multipolygons, clockwise polygons, and geofences that cross the antimeridian.

**Topics**
+ [

## Create a geofence collection
](#create-geofence-collection)
+ [

## Draw geofences
](#draw-geofences)
+ [

## Adding polygon geofences
](#draw-polygon-geofences)
+ [

## Adding circular geofences
](#draw-circle-geofences)

## Create a geofence collection


Create a geofence collection to store and manage geofences by using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To create a geofence collection using the Amazon Location console**

1. Open the Amazon Location Service console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. In the left navigation pane, choose **Geofence collections**.

1. Choose **Create geofence collection**.

1. Fill out the following boxes:
   + ****Name **** – Enter a unique name. For example, *ExampleGeofenceCollection*. Maximum 100 characters. Valid entries include alphanumeric characters, hyphens, periods, and underscores.
   + ****Description **** – Enter an optional description to differentiate your resources.

1. Under **EventBridge rule with CloudWatch as a target**, you can create an optional EventBridge rule to get started [reacting to geofence events.](location-events.md) This enables Amazon Location to publish events to Amazon CloudWatch Logs.

1. (Optional) Under **Tags**, enter a tag **Key** and **Value**. This adds a tag your new geofence collection. For more information, see [Tag your Amazon Location Service resources](tagging.md).

1. (Optional) Under **Customer managed key encryption**, you can choose to **Add a customer managed key**. This adds a symmetric customer managed key that you create, own, and manage over the default AWS owned encryption. For more information, see [Encrypting data at rest](encryption-at-rest.md).

1. Choose **Create geofence collection**.

------
#### [ API ]

**To create a geofence collection using the Amazon Location APIs**

Use the `[CreateGeofenceCollection](https://docs.aws.amazon.com/location-geofences/latest/APIReference/API_CreateGeofenceCollection.html)` operation from the Amazon Location Geofences APIs. 

The following example uses an API request to create a geofence collection called *ExampleGeofenceCollection*. The geofence collection is associated with a [customer managed AWS KMS key to encrypt customer data](encryption-at-rest.md).

```
POST /geofencing/v0/collections
Content-type: application/json

{
   "CollectionName": "ExampleGeofenceCollection",
   "Description": "Geofence collection 1 for shopping center",
   "KmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
   "Tags": { 
      "Tag1" : "Value1"
   }
}
```

------
#### [ AWS CLI ]

**To create a geofence collection using AWS CLI commands**

Use the `[create-geofence-collection](https://docs.aws.amazon.com/cli/latest/reference/location/create-geofence-collection.html)` command.

The following example uses an AWS CLI to create a geofence collection called *ExampleGeofenceCollection*. The geofence collection is associated with a [customer managed AWS KMS key to encrypt customer data](encryption-at-rest.md).

```
aws location \
  create-geofence-collection \
  --collection-name "ExampleGeofenceCollection" \
  --description "Shopping center geofence collection" \
  --kms-key-id "1234abcd-12ab-34cd-56ef-1234567890ab" \
  --tags Tag1=Value1
```

------

**Note**  
Billing depends on your usage. You may incur fees for the use of other AWS services. For more information, see [Amazon Location Service pricing](https://aws.amazon.com/location/pricing/).

## Draw geofences
Draw geofences

Now that you've created your geofence collection, you can define your geofences. Geofences are defined either as a polygon or as a circle. To draw a polygon geofence you can use a GeoJSON editing tool, such as [geojson.io](http://geojson.io/).

To create a geofence as a circle, you must define the center point of the circle, and the radius. For example, if you want to create a geofence to be notified whenever a device comes within 50 meters of a specific location, you would use the latitude and longitude of that location and specify the radius as 50 meters.

Using the Amazon Location Service APIs, you can also add metadata to your geofence, in the form of key-value pairs. These can be useful for storing information about the geofence, such as its type, or other information that is specific to your application. You can use this metadata when [Reacting to Amazon Location Service events with Amazon EventBridge](location-events.md).

## Adding polygon geofences


This section describes creating polygon geofences

### Draw geofences using a GeoJSON tool
Draw geofences using a GeoJSON tool

Now that you've created your geofence collection, you can define your geofences by using a GeoJSON editing tool, such as [geojson.io](http://geojson.io/).

**To create a GeoJSON file**

1. Open a GeoJSON editing tool. For example, geojson.io.

1. Choose the **Draw a polygon** icon and draw your area of interest.

1. Choose **Save**, then choose **GeoJSON** from the dropdown menu.

### Put GeoJSON geofences in a geofence collection


 You can use the resulting GeoJSON file to upload your geofences using the Amazon Location Service console, the AWS CLI, or the Amazon Location APIs:

------
#### [ Console ]

**To add a geofence to a geofence collection using the Amazon Location Service console**

1. Open the Amazon Location Service console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. In the left navigation pane, choose **Geofence collections**.

1. From the **Geofence collections** list, select the name link for the target geofence collection.

1. Under **Geofences**, choose **Create geofences**.

1. In the **Add geofences** window, drag, and drop your GeoJSON into the window. 

1. Choose **Add geofences**.

------
#### [ API ]

**To add geofences using the Amazon Location APIs**

Use the `[PutGeofence](https://docs.aws.amazon.com/location-geofences/latest/APIReference/API_PutGeofence.html)` operation from the Amazon Location Geofences APIs. 

The following example uses an API request to add a geofence given the ID *GEOFENCE-EXAMPLE1* to a geofence collection called *ExampleGeofenceCollection*. It also specifies a single geofence metadata property with the key `Type` and value `loadingArea`.

```
PUT /geofencing/v0/collections/ExampleGeofenceCollection/geofence/GEOFENCE-EXAMPLE1
    Content-type: application/json
    
    {
       "GeofenceProperties": {
          "Type" : "loadingArea"
       },
       "Geometry": { 
          "Polygon": [   
            [
                [-5.716667, -15.933333],
                [-14.416667, -7.933333],
                [-12.316667, -37.066667],
                [-5.716667, -15.933333]
            ]
          ]
       }
    }
```

Alternatively, you can add more than one geofence using the `[BatchPutGeofence](https://docs.aws.amazon.com/location-geofences/latest/APIReference/API_BatchPutGeofence.html)` operation. 

```
POST /geofencing/v0/collections/ExampleGeofenceCollection/put-geofences
    Content-type: application/json
    
    {
       "Entries": [ 
          {
             "GeofenceProperties": {
                "Type" : "loadingArea"
             },
             "GeofenceId": "GEOFENCE-EXAMPLE1",
             "Geometry": { 
                "Polygon": [ 
                   [ 
                      [-5.716667, -15.933333],
                      [-14.416667, -7.933333],
                      [-12.316667, -37.066667],
                      [-5.716667, -15.933333]
                   ]
                ]
             }
          }
       ]
    }
```

------
#### [ AWS CLI ]

**To add a geofence to a geofence collection using AWS CLI commands**

Use the `[put-geofence](https://docs.aws.amazon.com/cli/latest/reference/location/put-geofence.html)` command.

The following example uses an AWS CLI to add a geofence to a geofence collection called *ExampleGeofenceCollection*.

```
$ aws location \
        put-geofence \
            --collection-name ExampleGeofenceCollection \
            --geofence-id ExampleGeofenceTriangle \
            --geofence-properties '{"Type": "loadingArea"}' \
            --geometry 'Polygon=[[[-5.716667, -15.933333],[-14.416667, -7.933333],[-12.316667, -37.066667],[-5.716667, -15.933333]]]'
    {
        "CreateTime": "2020-11-11T00:16:14.487000+00:00",
        "GeofenceId": "ExampleGeofenceTriangle",
        "UpdateTime": "2020-11-11T00:19:59.894000+00:00"
    }
```

------

## Adding circular geofences


This section describes creating circular geofences. You must know the latitude and longitude of the point that you want to be the center of the circle, and the radius in meters of the circle. You can create circular geofences with the Amazon Location APIs or the AWS CLI.

------
#### [ API ]

**To add circular geofences using the Amazon Location APIs**

Use the `[PutGeofence](https://docs.aws.amazon.com/location/previous/APIReference/API_PutGeofence.html)` operation from the Amazon Location Geofences APIs. 

The following example uses an API request to add a geofence given the ID *GEOFENCE-EXAMPLE2* to a geofence collection called *ExampleGeofenceCollection*:

```
PUT /geofencing/v0/collections/ExampleGeofenceCollection/geofence/GEOFENCE-EXAMPLE2
    Content-type: application/json
    
    {
       "Geometry": { 
          "Circle": {   
            "Center": [-5.716667, -15.933333],
            "Radius": 50
          }
       }
    }
```

------
#### [ AWS CLI ]

**To add a circular geofence to a geofence collection using AWS CLI commands**

Use the `[put-geofence](https://docs.aws.amazon.com/cli/latest/reference/location/put-geofence.html)` command.

The following example uses an AWS CLI to add a geofence to a geofence collection called *ExampleGeofenceCollection*.

```
$ aws location \
        put-geofence \
            --collection-name ExampleGeofenceCollection \
            --geofence-id ExampleGeofenceCircle \
            --geometry 'Circle={Center=[-5.716667, -15.933333], Radius=50}'
```

**Note**  
You can also put JSON for complex geometry into its own file as in the following example.  

```
$ aws location \
        put-geofence \
            --collection-name ExampleGeofenceCollection \
            --geofence-id ExampleGeofenceCircle \
            --geometry file:circle.json
```
In the example, the circle.json file includes JSON for the circle geometry.  

```
{
    "Circle": {
        "Center": [-74.006975, 40.717127],
        "Radius": 287.7897969218057
    }
}
```

------

# Start tracking with Amazon Location
Start tracking

This section guides you through building a tracking application that captures device locations.

**Topics**
+ [

## Create a tracker
](#start-create-tracker)
+ [

## Authenticating your requests
](#tracking-identity-pool)
+ [

## Update your tracker with a device position
](#send-location-updates)
+ [

## Get a device's location history from a tracker
](#get-location-history)
+ [

## List your device positions
](#list-device-positions)

## Create a tracker


Create a tracker resource to store and process position updates from your devices. You can use the Amazon Location Service console, the AWS CLI, or the Amazon Location APIs. 

Each position update stored in your tracker resources can include a measure of position accuracy, and up to three fields of metadata about the position or device that you want to store. The metadata is stored as key-value pairs, and can store information such as speed, direction, tire pressure, or engine temperature.

Trackers filter position updates as they are received. This reduces visual noise in your device paths (called *jitter*), and reduces the number of false geofence entry and exit events. This also helps manage costs by reducing the number of geofence evaluations initiated.

Trackers offer three position filtering options to help manage costs and reduce jitter in your location updates.
+ **Accuracy-based** – *Use with any device that provides an accuracy measurement. Most mobile devices provide this information.* The accuracy of each position measurement is affected by many environmental factors, including GPS satellite reception, landscape, and the proximity of Wi-Fi and Bluetooth devices. Most devices, including most mobile devices, can provide an estimate of the accuracy of the measurement along with the measurement. With `AccuracyBased` filtering, Amazon Location ignores location updates if the device moved less than the measured accuracy. For example, if two consecutive updates from a device have an accuracy range of 5 m and 10 m, Amazon Location ignores the second update if the device has moved less than 15 m. Amazon Location neither evaluates ignored updates against geofences, nor stores them.

   When accuracy is not provided, it is treated as zero, and the measurement is considered perfectly accurate.
**Note**  
You can also use accuracy-based filtering to remove all filtering. If you select accuracy-based filtering, but override all accuracy data to zero, or omit the accuracy entirely, then Amazon Location will not filter out any updates.
+ **Distance-based** – *Use when your devices do not provide an accuracy measurement, but you still want to take advantage of filtering to reduce jitter and manage costs.* `DistanceBased` filtering ignores location updates in which devices have moved less than 30 m (98.4 ft). When you use `DistanceBased` position filtering, Amazon Location neither evaluates these ignored updates against geofences nor stores the updates.

  The accuracy of most mobile devices, including the average accuracy of iOS and Android devices, is within 15 m. In most applications, `DistanceBased` filtering can reduce the effect of location inaccuracies when displaying device trajectory on a map, and the bouncing effect of multiple consecutive entry and exit events when devices are near the border of a geofence. It can also help reduce the cost of your application, by making fewer calls to evaluate against linked geofences or retrieve device positions.
+ **Time-based** – (default) *Use when your devices send position updates very frequently (more than once every 30 seconds), and you want to achieve near real-time geofence evaluations without storing every update. *In `TimeBased` filtering, every location update is evaluated against linked geofence collections, but not every location update is stored. If your update frequency is more often than 30 seconds, only one update per 30 seconds is stored for each unique device ID.

**Note**  
Be mindful of the costs of your tracking application when deciding your filtering method and the frequency of position updates. You are billed for every location update and once for evaluating the position update against each linked geofence collection. For example, when using time-based filtering, if your tracker is linked to two geofence collections, every position update will count as one location update request and two geofence collection evaluations. If you are reporting position updates every 5 seconds for your devices and using time-based filtering, you will be billed for 720 location updates and 1,440 geofence evaluations per hour for each device.  
Your bill is not affected by the number of geofences in each collection. Since each geofence collection may contain up to 50,000 geofences, you may want to combine your geofences into fewer collections, where possible, to reduce your cost of geofence evaluations.

By default, you will get EventBridge events each time a tracked device enters or exits a linked geofence. For more information, see [Tutorial: Link a tracker to a geofence collection in Amazon Location](associate-consumer.md).

You can enable events for all filtered position updates for a tracker resource. For more information, see [Enable update events for a tracker](location-events.md#enable-update-events).

**Note**  
If you wish to encrypt your data using your own AWS KMS customer managed key, then the Bounding Polygon Queries feature will be disabled by default. This is because by using this Bounding Polygon Queries feature, a representation of your device positions will not be encrypted using the your AWS KMS managed key. However, the exact device position is still encrypted using your managed key.  
You can choose to opt-in to the Bounding Polygon Queries feature by setting the `KmsKeyEnableGeospatialQueries` parameter to true when creating or updating a Tracker.

------
#### [ Console ]

**To create a tracker using the Amazon Location console**

1. Open the Amazon Location Service console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. In the left navigation pane, choose **Trackers**.

1. Choose **Create tracker**.

1. Fill the following fields:
   + ****Name **** – Enter a unique name. For example, *ExampleTracker*. Maximum 100 characters. Valid entries include alphanumeric characters, hyphens, periods, and underscores.
   + ****Description** ** – Enter an optional description.

1. Under **Position filtering**, choose the option that best fits how you intend to use your tracker resource. If you do not set **Position filtering**, the default setting is `TimeBased`. For more information, see [Learn about trackers in Amazon Location Service](tracking-overview.md) in this guide, and `[PositionFiltering](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_CreateTracker.html#locationtrackers-CreateTracker-request-PositionFiltering)` in the Amazon Location Service Trackers API Reference.

1. (Optional) Under **Tags**, enter a tag **Key** and **Value**. This adds a tag your new geofence collection. For more information, see [Tagging your resources](tagging.md).

1. (Optional) Under **Customer managed key encryption**, you can choose to **Add a customer managed key**. This adds a symmetric customer managed key that you create, own, and manage over the default AWS owned encryption. For more information, see [Encrypting data at rest](encryption-at-rest.md).

1. (Optional) Under **KmsKeyEnableGeospatialQueries**, you can choose to enable **Geospatial Queries**. This allows you use the Bounding Polygon Queries feature, while encrypting your data using a customer AWS KMS managed key.
**Note**  
When you use the Bounding Polygon Queries feature a representation of your device positions is not be encrypted using the your AWS KMS managed key. However, the exact device position is still encrypted using your managed key.

1. (Optional) Under **EventBridge configuration**, you can choose to enable EventBridge events for filtered position updates. This will send an event each time a position update for a device in this tracker meets the position filtering evaluation.

1. Choose **Create tracker**.

------
#### [ API ]

**To create a tracker by using the Amazon Location APIs**

Use the `[CreateTracker](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_CreateTracker.html)` operation from the Amazon Location Trackers APIs.

The following example uses an API request to create a tracker called *ExampleTracker*. The tracker resource is associated with a [customer managed AWS KMS key to encrypt customer data](encryption-at-rest.md), and does not [enable position updates in EventBridge](location-events.md#enable-update-events).

```
POST /tracking/v0/trackers
Content-type: application/json

{
   
   "TrackerName": "ExampleTracker",
   "Description": "string",
   "KmsKeyEnableGeospatialQueries": false, 
   "EventBridgeEnabled": false,
   "KmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
   "PositionFiltering": "AccuracyBased",
   "Tags": { 
      "string" : "string" 
   }
}
```

**Create a tracker with `KmsKeyEnableGeospatialQueries` enabled**

The following example has the parameter `KmsKeyEnableGeospatialQueries` set to true. This allows you use the Bounding Polygon Queries feature, while encrypting your data using a customer AWS KMS managed key.

For information on using the Bounding Polygon Queries feature, see [List your device positions](#list-device-positions)

**Note**  
When you use the Bounding Polygon Queries feature a representation of your device positions is not be encrypted using the your AWS KMS managed key. However, the exact device position is still encrypted using your managed key.

```
POST /tracking/v0/trackers
Content-type: application/json

{
   
   "TrackerName": "ExampleTracker",
   "Description": "string",
   "KmsKeyEnableGeospatialQueries": true, 
   "EventBridgeEnabled": false,
   "KmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
   "PositionFiltering": "AccuracyBased",
   "Tags": { 
      "string" : "string" 
   }
}
```

------
#### [ AWS CLI ]

**To create a tracker using AWS CLI commands**

Use the `[create-tracker](https://docs.aws.amazon.com/cli/latest/reference/location/create-tracker.html)` command.

The following example uses the AWS CLI to create a tracker called *ExampleTracker*. The tracker resource is associated with a [customer managed AWS KMS key to encrypt customer data](encryption-at-rest.md), and does not [enable position updates in EventBridge](location-events.md#enable-update-events).

```
aws location \
  create-tracker \
  --tracker-name "ExampleTracker" \
  --position-filtering "AccuracyBased" \
  --event-bridge-enabled false \
  --kms-key-enable-geospatial-queries false \
  --kms-key-id "1234abcd-12ab-34cd-56ef-1234567890ab"
```

**Create a tracker with `KmsKeyEnableGeospatialQueries` enabled**

The following example has the parameter `KmsKeyEnableGeospatialQueries` set to true. This allows you use the Bounding Polygon Queries feature, while encrypting your data using a customer AWS KMS managed key.

For information on using the Bounding Polygon Queries feature, see [List your device positions](#list-device-positions)

**Note**  
When you use the Bounding Polygon Queries feature a representation of your device positions is not be encrypted using the your AWS KMS managed key. However, the exact device position is still encrypted using your managed key.

```
aws location \
  create-tracker \
  --tracker-name "ExampleTracker" \
  --position-filtering "AccuracyBased" \
  --event-bridge-enabled false \
  --kms-key-enable-geospatial-queries true \
  --kms-key-id "1234abcd-12ab-34cd-56ef-1234567890ab"
```

------

**Note**  
Billing depends on your usage. You may incur fees for the use of other AWS services. For more information, see [Amazon Location Service pricing](https://aws.amazon.com/location/pricing/).

You can edit the **Description**, **Position filtering**, and **EventBridge configuration** after the tracker is created by choosing **Edit tracker**.

## Authenticating your requests
Create an unauthenticated identity pool

Once you create a tracker resource and you're ready to begin evaluating device positions against geofences, choose how you would authenticate your requests:
+ To explore ways you can access the services, see [Accessing Amazon Location Service](how-to-access.md).
+ If you want to publish device positions with unauthenticated requests,you may want to use Amazon Cognito.

  **Example**

  The following example shows using an Amazon Cognito identity pool for authorization, using [AWS JavaScript SDK v3](https://aws.amazon.com/sdk-for-javascript/), and the Amazon Location [JavaScript Authentication helper](loc-sdk-auth.md).

  ```
  import { LocationClient, BatchUpdateDevicePositionCommand } from "@aws-sdk/client-location";
  import { withIdentityPoolId } from "@aws/amazon-location-utilities-auth-helper";
  
  // Unauthenticated identity pool you created
  const identityPoolId = "us-east-1:1234abcd-5678-9012-abcd-sample-id";
  
  // Create an authentication helper instance using credentials from Cognito
  const authHelper = await withIdentityPoolId(identityPoolId);
  
  const client = new LocationClient({
    region: "us-east-1", // The region containing both the identity pool and tracker resource
    ...authHelper.getLocationClientConfig(), // Provides configuration required to make requests to Amazon Location
  });
  
  const input = {
    TrackerName: "ExampleTracker",
    Updates: [
      {
        DeviceId: "ExampleDevice-1",
        Position: [-123.4567, 45.6789],
        SampleTime: new Date("2020-10-02T19:09:07.327Z"),
      },
      {
        DeviceId: "ExampleDevice-2",
        Position: [-123.123, 45.123],
        SampleTime: new Date("2020-10-02T19:10:32Z"),
      },
    ],
  };
  
  const command = new BatchUpdateDevicePositionCommand(input);
  
  // Send device position updates
  const response = await client.send(command);
  ```

## Update your tracker with a device position
Update your tracker with a device position

To track your devices, you can post device position updates to your tracker. You can later retrieve these device positions or the device position history from your tracker resource.

Each position update must include the device ID, a timestamp , and a position. You may optionally include other metadata, including accuracy and up to 3 key-value pairs for your own use.

If your tracker is linked to one or more geofence collections, updates will be evaluated against those geofences (following the filtering rules that you specified for the tracker). If a device breaches a geofenced area (by moving from inside the area to outside, or vice versa), you will receive events in EventBridge. These `ENTER` or `EXIT` events include the position update details, including the device ID, the timestamp, and any associated metadata.

**Note**  
For more information about position filtering, see [Create a tracker](#start-create-tracker).  
For more information about geofence events, see [Reacting to Amazon Location Service events with Amazon EventBridge](location-events.md).

Use either of these methods to send device updates:
+ [Send MQTT updates](https://docs.aws.amazon.com/location/previous/developerguide/tracking-using-mqtt.html) to an AWS IoT Core resource and link it to your tracker resource.
+ Send location updates using the Amazon Location Trackers API, by using the AWS CLI, or the Amazon Location APIs. You can use the [AWS SDKs](location-actions.md) to call the APIs from your iOS or Android application.

------
#### [ API ]

**To send a position update using the Amazon Location APIs**

Use the `[BatchUpdateDevicePosition](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_BatchUpdateDevicePosition.html)` operation from the Amazon Location Trackers APIs. 

The following example uses an API request to post a device position update for *ExampleDevice* to a tracker *ExampleTracker*.

```
POST /tracking/v0/trackers/ExampleTracker/positions
Content-type: application/json
{
 "Updates": [
    {
    "DeviceId": "1",
    "Position": [
   -123.12245146162303, 49.27521118043802
    ],
    "SampleTime": "2022-10-24T19:09:07.327Z",
     "PositionProperties": { 
            "name" : "device1" 
         },
         "Accuracy": { 
            "Horizontal": 10
         }
    },

    {
    "DeviceId": "2",
    "Position": [
   -123.1230104928471, 49.27752402723152
    ],
    "SampleTime": "2022-10-02T19:09:07.327Z"
    },
    {
    "DeviceId": "3",
    "Position": [
    -123.12325592118916, 49.27340530543111
    ],
    "SampleTime": "2022-10-02T19:09:07.327Z"
    },
    {
    "DeviceId": "4",
    "Position": [
    -123.11958813096311, 49.27774641063121
    ],
    "SampleTime": "2022-10-02T19:09:07.327Z"
    },
    {
    "DeviceId": "5",
    "Position": [
    -123.1277418058896, 49.2765989015285
    ],
    "SampleTime": "2022-10-02T19:09:07.327Z"
    },
    {
    "DeviceId": "6",
    "Position": [
   -123.11964267059481, 49.274188155916534
    ],
    "SampleTime": "2022-10-02T19:09:07.327Z"
    }
    ]
}
```

------
#### [ AWS CLI ]

**To send a position update using AWS CLI commands**

Use the `[batch-update-device-position](https://docs.aws.amazon.com/cli/latest/reference/location/batch-update-device-position.html)` command.

The following example uses an AWS CLI to post a device position update for *ExampleDevice-1* and *ExampleDevice-2* to a tracker *ExampleTracker*. 

```
aws location batch-update-device-position \
--tracker-name ExampleTracker \
--updates '[{"DeviceId":"ExampleDevice-1","Position":[-123.123,47.123],"SampleTime":"2021-11-30T21:47:25.149Z"},{"DeviceId":"ExampleDevice-2","Position":[-123.123,47.123],"SampleTime":"2021-11-30T21:47:25.149Z","Accuracy":{"Horizontal":10.30},"PositionProperties":{"field1":"value1","field2":"value2"}}]'
```

------

## Get a device's location history from a tracker
Get a device's location history

 Your Amazon Location tracker resource maintains the location history of all your tracked devices for a period of 30 days. You can retrieve device location history, including all associated metadata, from your tracker resource. The following examples use the AWS CLI, or the Amazon Location APIs.

------
#### [ API ]

**To get the device location history from a tracker using the Amazon Location APIs**

Use the `[GetDevicePositionHistory](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_GetDevicePositionHistory.html)` operation from the Amazon Location Trackers APIs. 

The following example uses an API URI request to get the device location history of *ExampleDevice* from a tracker called *ExampleTracker* starting from `19:05:07` (inclusive) and ends at `19:20:07` (exclusive) on `2020–10–02`.

```
POST /tracking/v0/trackers/ExampleTracker/devices/ExampleDevice/list-positions 
Content-type: application/json
{
  "StartTimeInclusive": "2020-10-02T19:05:07.327Z",
  "EndTimeExclusive": "2020-10-02T19:20:07.327Z"
}
```

------
#### [ AWS CLI ]

**To get the device location history from a tracker using AWS CLI commands**

Use the `[get-device-position-history](https://docs.aws.amazon.com/cli/latest/reference/location/get-device-position-history.html)` command.

The following example uses an AWS CLI to get the device location history of *ExampleDevice* from a tracker called *ExampleTracker* starting from `19:05:07` (inclusive) and ends at `19:20:07` (exclusive) on `2020–10–02`.

```
aws location \
    get-device-position-history \
        --device-id "ExampleDevice" \
        --start-time-inclusive "2020-10-02T19:05:07.327Z" \
        --end-time-exclusive "2020-10-02T19:20:07.327Z" \
        --tracker-name "ExampleTracker"
```

------

## List your device positions


You can view a list device positions for a tracker using the AWS CLI, or the Amazon Location APIs, with the ListDevicePositions API. When you call the ListDevicePositions API, a list of the latest positions for all devices associated with a given tracker is returned. By default this API returns 100 of the latest device positions per page of results for a given tracker. To only return devices within a specific region use the `FilterGeometry` parameter to create a Bounding Polygon Query. This way when you call ListDevicePositions, only devices inside the polygon will be returned.

**Note**  
If you wish to encrypt your data using your own AWS KMS customer managed key, then the Bounding Polygon Queries feature will be disabled by default. This is because by using this feature, a representation of your device positions will not be encrypted using the your AWS KMS managed key. The exact device position, however; is still encrypted using your managed key.  
You can choose to opt-in to the Bounding Polygon Queries feature. This is done by setting the `KmsKeyEnableGeospatialQueries` parameter to true when creating or updating a Tracker.

------
#### [ API ]

Use the `[ListDevicePositions](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_ListDevicePositions.html)` operation from the Amazon Location Trackers APIs.

The following example is an API request to get a list of device positions in polygonal area, using the optional parameter `[FilterGeometry](https://docs.aws.amazon.com/)`. The example returns 3 device locations present in the area defined by the `Polygon` array.

```
POST /tracking/v0/trackers/TrackerName/list-positions HTTP/1.1
Content-type: application/json

{
   "FilterGeometry": {
        "Polygon": [
          [
            [
              -123.12003339442259,
              49.27425121147397
            ],
            [
              -123.1176984148229,
              49.277063620879744
            ],
            [
              -123.12389509145294,
              49.277954183760926
            ],
            [
              -123.12755921328647,
              49.27554025235713
            ],
            [
              -123.12330236586217,
              49.27211836076236
            ],
            [
              -123.12003339442259,
              49.27425121147397
            ]
          ]
        ]
    },
   "MaxResults": 3,
   "NextToken": "1234-5678-9012"
}
```

The following is an example response for `[ListDevicePositions](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_ListDevicePositions.html)`:

```
{
    "Entries": [
        {
            "DeviceId": "1",
            "SampleTime": "2022-10-24T19:09:07.327Z",
            "Position": [
                -123.12245146162303,
                49.27521118043802
            ],
            "Accuracy": {
                "Horizontal": 10
            },
            "PositionProperties": {
                "name": "device1"
            }
        },
        {
            "DeviceId": "3",
            "SampleTime": "2022-10-02T19:09:07.327Z",
            "Position": [
                -123.12325592118916,
                49.27340530543111
            ]
        },
        {
            "DeviceId": "2",
            "SampleTime": "2022-10-02T19:09:07.327Z",
            "Position": [
                -123.1230104928471,
                49.27752402723152
            ]
        }
    ],
   "NextToken": "1234-5678-9012"
}
```

------
#### [ CLI ]

Use the `[list-trackers](https://docs.aws.amazon.com/cli/latest/reference/location/list-trackers.html)` command.

The following example is an AWS CLI to get a list of devices in a polygonal area. 

```
aws location list-device-positions TODO: add arguments add props for filter geo
```

------

# Tutorial: Link a tracker to a geofence collection in Amazon Location
Tutorial: Link a tracker to a geofence collection

Now that you have a geofence collection and a tracker, you can link them together so that location updates are automatically evaluated against all of your geofences. If you don’t want to evaluate all location updates, or alternatively, if you aren't storing some of your locations in a tracker resource, you can [evaluate device positions against geofences](https://docs.aws.amazon.com/location/previous/developerguide/evaluate-geofences.html) on demand.

When device positions are evaluated against geofences, events are generated. You can set an action to these events. For more information about actions that you can set for geofence events, see [Reacting to Amazon Location Service events with Amazon EventBridge](https://docs.aws.amazon.com/location/previous/developerguide/location-events.html).

An Amazon Location event includes the attributes of the device position update that generates it and some attributes of the geofence that is entered or exited. For more information about the data included in a geofence event, see [Amazon EventBridge event examples for Amazon Location Service](location-events.md#example-event).

The following examples link a tracker resource to a geofence collection using the console, the AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To link a tracker resource to a geofence collection using the Amazon Location Service console**

1. Open the Amazon Location Service console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. In the left navigation pane, choose **Trackers**.

1. Under **Device trackers**, select the name link of the target tracker.

1. Under **Linked Geofence Collections**, choose **Link Geofence Collection**.

1. In the **Linked Geofence Collection** window, select a geofence collection from the dropdown menu.

1. Choose **Link**.

After you link the tracker resource, it will be assigned an **Active** status.

------
#### [ API ]

**To link a tracker resource to a geofence collection using the Amazon Location APIs**

Use the `[AsssociateTrackerConsumer](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_AssociateTrackerConsumer.html)` operation from the Amazon Location Trackers APIs. 

The following example uses an API request that associates *ExampleTracker* with a geofence collection using its [Amazon Resource Name ](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)(ARN).

```
POST /tracking/v0/trackers/ExampleTracker/consumers
Content-type: application/json

{
   "ConsumerArn": "arn:aws:geo:us-west-2:123456789012:geofence-collection/ExampleGeofenceCollection"
}
```

------
#### [ AWS CLI ]

**To link a tracker resource to a geofence collection using AWS CLI commands**

Use the `[associate-tracker-consumer](https://docs.aws.amazon.com/cli/latest/reference/location/associate-tracker-consumer.html)` command. 

The following example uses an AWS CLI to create a geofence collection called *ExampleGeofenceCollection*.

```
aws location \
    associate-tracker-consumer \
        --consumer-arn "arn:aws:geo:us-west-2:123456789012:geofence-collection/ExampleGeofenceCollection" \
        --tracker-name "ExampleTracker"
```

------

# Evaluate device positions against geofences in Amazon Location
Evaluate device positions against geofences

There are two ways to evaluate positions against geofences to generate geofence events: 
+ You can link Trackers and Geofence Collections. For more information, see the section: [Tutorial: Link a tracker to a geofence collection in Amazon Location](associate-consumer.md).
+ You can make a direct request to the geofence collection resource to evaluate one or more positions, using the [BatchEvaluateGeofences](https://docs.aws.amazon.com//location/previous/APIReference/API_BatchEvaluateGeofences.html) API.

Additionally, you can forecast incoming geofence events for a device entering, exiting, or remaining idle within a geofence. Use the [ForecastGeofenceEvents](https://docs.aws.amazon.com//location/previous/APIReference/API_ForecastGeofenceEvents.html) API to forecast events.

If you also want to track your device location history or display locations on a map, link the tracker with a geofence collection. Alternatively, you may not want to evaluate all location updates, or you don't intend to store location data in a tracker resource. If either of these is the case, you can make a direct request to the geofence collection and evaluate one or more device positions against its geofences.

Evaluating device positions against geofences generates events. You can react to these events and route them to other AWS services. For more information about actions that you can take when receiving geofence events, see [Reacting to Amazon Location Service events with Amazon EventBridge](https://docs.aws.amazon.com/location/previous/developerguide/location-events.html).

An Amazon Location event includes the attributes of the device position update that generates it, including the time, position, accuracy, and key-value metadata, and some attributes of the geofence that is entered or exited. For more information about the data included in a geofence event, see [Amazon EventBridge event examples for Amazon Location Service](location-events.md#example-event).

The following examples use the AWS CLI, or the Amazon Location APIs.

------
#### [ API ]

**To evaluate device positions against the position of geofences using the Amazon Location APIs**

Use the `[BatchEvaluateGeofences](https://docs.aws.amazon.com/location-geofences/latest/APIReference/API_BatchEvaluateGeofences.html)` operation from the Amazon Location Geofences APIs. 

The following example uses an API request to evaluate the position of device *ExampleDevice* to an associated geofence collection *ExampleGeofenceCollection*. Replace these values with your own geofence and device IDs.

```
POST /geofencing/v0/collections/ExampleGeofenceCollection/positions HTTP/1.1
Content-type: application/json

{
   "DevicePositionUpdates": [ 
      { 
         "DeviceId": "ExampleDevice",
         "Position": [-123.123, 47.123],
         "SampleTime": "2021-11-30T21:47:25.149Z",
         "Accuracy": {
            "Horizontal": 10.30
         },
         "PositionProperties": {
            "field1": "value1",
            "field2": "value2"
         }
      }
   ]
}
```

------
#### [ AWS CLI ]

**To evaluate device positions against the position of geofences using AWS CLI commands**

Use the `[batch-evaluate-geofences](https://docs.aws.amazon.com/cli/latest/reference/location/batch-evaluate-geofences.html)` command. 

The following example uses an AWS CLI to evaluate the position of *ExampleDevice* against an associated geofence collection *ExampleGeofenceCollection*. Replace these values with your own geofence and device IDs.

```
aws location \
    batch-evaluate-geofences \
        --collection-name ExampleGeofenceCollection \
        --device-position-updates '[{"DeviceId":"ExampleDevice","Position":[-123.123,47.123],"SampleTime":"2021-11-30T21:47:25.149Z","Accuracy":{"Horizontal":10.30},"PositionProperties":{"field1":"value1","field2":"value2"}}]'
```

------

Evaluating device positions against geofences generates events. Traditionally you can react to the events by using [Amazon EventBridge](https://docs.aws.amazon.com//location/previous/developerguide/evaluate-geofences.html), but this process only lets you react to events after then have happened. If you need to anticipate when a device enters or exits a geofence, for example if a device is crossing a border and will be subject to a different regulations as a consequence, then you can use the [ForecastGeofenceEvents](https://docs.aws.amazon.com//location/previous/APIReference/API_ForecastGeofenceEvents.html) API to predict future geofence events.

The [ForecastGeofenceEvents](https://docs.aws.amazon.com//location/previous/APIReference/API_ForecastGeofenceEvents.html) API uses criteria such as the device's time-to-breach, proximity, speed, and position to predict events. There API will return a ` ForecastedBreachTime`, which signals the estimated time the geofence event will occur.

The following example uses the Amazon Location APIs.

------
#### [ API ]

**To forecast geofence events using the Amazon Location APIs**

Use the ` [ForecastGeofenceEvents](https://docs.aws.amazon.com//location/previous/APIReference/API_ForecastGeofenceEvents.html)` operation from the Amazon Location Geofences APIs. 

The following example uses an API request to forecast geofence events for an *ExampleDevice* relative to an *ExampleGeofence*. Replace these values with your own geofence and device IDs.

```
POST /geofencing/v0/collections/CollectionName/forecast-geofence-events HTTP/1.1
Content-type: application/json

{
   "DeviceState": { 
      "Position": [ number ],
      "Speed": number
   },
   "DistanceUnit": "string",
   "MaxResults": number,
   "NextToken": "string",
   "SpeedUnit": "string",
   "TimeHorizonMinutes": number
}
```

------

# Tutorial: Verify device positions with Amazon Location
Tutorial: Verify device positions

To check the integrity of a device position use the [VerifyDevicePosition](https://docs.aws.amazon.com//location/previous/APIReference/API_VerifyDevicePosition.html) API. This API returns information about the integrity of the device's position, by evaluating properties such as the device's cell signal, Wi-Fi access point, Ipv4 address, and if a proxy is in use.

## Prerequisites


Before being able to use the listed APIs for device verification, make sure you have the following prerequisite:
+ You have created a tracker for the device or devices you want to check. For more information, see [Start tracking with Amazon Location](start-tracking.md).

The following example shows a request for the Amazon Location [VerifyDevicePosition](https://docs.aws.amazon.com//location/previous/APIReference/API_VerifyDevicePosition.html) API.

------
#### [ API ]

**To verify device positions using the Amazon Location APIs**

Use the `[VerifyDevicePosition](https://docs.aws.amazon.com/location/previous/APIReference/API_VerifyDevicePosition.html)` operation from the Amazon Location Tracking APIs.

The following example shows an API request to evaluate the integrity of the position of a device. Replace these values with your own device IDs.

```
POST /tracking/v0/trackers/TrackerName/positions/verify HTTP/1.1
Content-type: application/json

{
   "DeviceState": { 
      "Accuracy": { 
         "Horizontal": number
      },
      "CellSignals": { 
         "LteCellDetails": [ 
            { 
               "CellId": number,
               "LocalId": { 
                  "Earfcn": number,
                  "Pci": number
               },
               "Mcc": number,
               "Mnc": number,
               "NetworkMeasurements": [ 
                  { 
                     "CellId": number,
                     "Earfcn": number,
                     "Pci": number,
                     "Rsrp": number,
                     "Rsrq": number
                  }
               ],
               "NrCapable": boolean,
               "Rsrp": number,
               "Rsrq": number,
               "Tac": number,
               "TimingAdvance": number
            }
         ]
      },
      "DeviceId": "ExampleDevice",
      "Ipv4Address": "string",
      "Position": [ number ],
      "SampleTime": "string",
      "WiFiAccessPoints": [ 
         { 
            "MacAddress": "string",
            "Rss": number
         }
      ]
   },
   "DistanceUnit": "string"
}
```

------

**Note**  
The **Integrity SDK** provides enhanced features related to device verification, and it is available for use by request. To get access to the SDK, contact [Sales Support](https://aws.amazon.com/contact-us/sales-support/?pg=locationprice&cta=herobtn).

# Reacting to Amazon Location Service events with Amazon EventBridge
Reacting to events with EventBridge

Amazon EventBridge is a serverless event bus that efficiently connects applications together using data from AWS services like Amazon Location. EventBridge receives events from Amazon Location and routes that data to targets like AWS Lambda. You can set up routing rules to determine where to send your data to build application architectures that react in real time.

Only geofence events (`ENTER` and `EXIT` events, as devices enter or leave the geofenced areas) are sent to EventBridge by default. You can also enable all filtered position update events for a tracker resource. For more information, see [Enable update events for a tracker](#enable-update-events).

For more information, see [the Events and Event Patterns](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-and-event-patterns.html) in *the Amazon EventBridge User Guide*.

**Topics**
+ [

## Enable update events for a tracker
](#enable-update-events)
+ [

## Create event rules for Amazon Location
](#create-event-rule)
+ [

## Amazon EventBridge event examples for Amazon Location Service
](#example-event)

## Enable update events for a tracker


By default, Amazon Location sends only `ENTER` and `EXIT` geofence events to EventBridge. You can enable all filtered position `UPDATE` events for a tracker to be sent to EventBridge. You can do this when you [create](https://docs.aws.amazon.com/location/previous/APIReference/API_CreateTracker.html) or [update](https://docs.aws.amazon.com/location/previous/APIReference/API_UpdateTracker.html) a tracker.

For example, to update an existing tracker using the AWS CLI, you can use the following command (use the name of your tracker resource in place of *MyTracker*).

```
aws location update-tracker --tracker-name MyTracker --event-bridge-enabled
```

To turn off position events for a tracker, you must use the API or the Amazon Location Service console.

## Create event rules for Amazon Location
Create event rules

You can create [up to 300 rules per event bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-quota.html) in EventBridge to configure actions taken in response to an Amazon Location event. 

For example, you can create a rule for geofence events where a push notification will be sent when a phone is detected within a geofenced boundary.

**To create a rule for Amazon Location events**

Using the following values, [create an EventBridge rule](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule.html) based on Amazon Location events:
+ For **Rule type**, choose **Rule with an event pattern**.
+ In the **Event pattern** box, add the following pattern:

  ```
  {
    "source": ["aws.geo"],
    "detail-type": ["Location Geofence Event"]
  }
  ```

  To create a rule for tracker position updates, you can instead use the following pattern:

  ```
  {
    "source": ["aws.geo"],
    "detail-type": ["Location Device Position Event"]
  }
  ```

  You can optionally specify only `ENTER` or `EXIT` events by adding a `detail` tag (if your rule is for tracker position updates, there is only a single `EventType`, so there is no need to filter on it):

  ```
  {
    "source": ["aws.geo"],
    "detail-type": ["Location Geofence Event"],
    "detail": {
      "EventType": ["ENTER"]
    }
  }
  ```

  You can also optionally filter on properties of the position or geofence:

  ```
  {
    "source": ["aws.geo"],
    "detail-type": ["Location Geofence Event"],
    "detail": {
      "EventType": ["ENTER"],
      "GeofenceProperties": {
        "Type": "LoadingDock"
      },
      "PositionProperties": {
        "VehicleType": "Truck"
      }
    }
  }
  ```
+ For **Select targets**, choose the target action to take when an event is received from Amazon Location Service.

  For example, use an Amazon Simple Notification Service (SNS) topic to send an email or text message when an event occurs. You first need to create an Amazon SNS topic using the Amazon SNS console. For more information, see [Using Amazon SNS for user notifications](https://docs.aws.amazon.com//sns/latest/dg/sns-user-notifications.html).

**Warning**  
It's best practice to confirm that the event rule was successfully applied or your automated action may not initiate as expected. To verify your event rule, initiate conditions for the event rule. For example, simulate a device entering a geofenced area. 

You can also capture all events from Amazon Location, by just excluding the `detail-type` section. For example:

```
{
  "source": [
    "aws.geo"
  ]
}
```

**Note**  
The same event may be delivered more than one time. You can use the event id to de-duplicate the events that you receive.

## Amazon EventBridge event examples for Amazon Location Service
Event examples

The following is an example of an event for entering a geofence initiated by calling `BatchUpdateDevicePosition`.

```
{
  "version": "0",
  "id": "aa11aa22-33a-4a4a-aaa5-example",
  "detail-type": "Location Geofence Event",
  "source": "aws.geo",
  "account": "636103698109",
  "time": "2020-11-10T23:43:37Z",
  "region": "eu-west-1",
  "resources": [
    "arn:aws:geo:eu-west-1:0123456789101:geofence-collection/GeofenceEvents-GeofenceCollection_EXAMPLE",
    "arn:aws:geo:eu-west-1:0123456789101:tracker/Tracker_EXAMPLE"
  ],
  "detail": {
    "EventType": "ENTER",
    "GeofenceId": "polygon_14",
    "DeviceId": "Device1-EXAMPLE",
    "SampleTime": "2020-11-10T23:43:37.531Z",
    "Position": [
      -123.12390073297821,
      49.23433613216247
    ],
    "Accuracy": {
      "Horizontal": 15.3
    },
    "GeofenceProperties": {
      "ExampleKey1": "ExampleField1",
      "ExampleKey2": "ExampleField2"
    },
    "PositionProperties": {
      "ExampleKey1": "ExampleField1",
      "ExampleKey2": "ExampleField2"
    }
  }
}
```

The following is an example of an event for exiting a geofence initiated by calling `BatchUpdateDevicePosition`.

```
{
  "version": "0",
  "id": "aa11aa22-33a-4a4a-aaa5-example",
  "detail-type": "Location Geofence Event",
  "source": "aws.geo",
  "account": "123456789012",
  "time": "2020-11-10T23:41:44Z",
  "region": "eu-west-1",
  "resources": [
    "arn:aws:geo:eu-west-1:0123456789101:geofence-collection/GeofenceEvents-GeofenceCollection_EXAMPLE",
    "arn:aws:geo:eu-west-1:0123456789101:tracker/Tracker_EXAMPLE"
  ],
  "detail": {
    "EventType": "EXIT",
    "GeofenceId": "polygon_10",
    "DeviceId": "Device1-EXAMPLE",
    "SampleTime": "2020-11-10T23:41:43.826Z",
    "Position": [
      -123.08569321875426,
      49.23766166742559
    ],
    "Accuracy": {
      "Horizontal": 15.3
    },
    "GeofenceProperties": {
      "ExampleKey1": "ExampleField1",
      "ExampleKey2": "ExampleField2"
    },
    "PositionProperties": {
      "ExampleKey1": "ExampleField1",
      "ExampleKey2": "ExampleField2"
    }
  }
}
```

The following is an example of an event for a position update, initiated by calling `BatchUpdateDevicePosition`.

```
{
  "version": "0",
  "id": "aa11aa22-33a-4a4a-aaa5-example",
  "detail-type": "Location Device Position Event",
  "source": "aws.geo",
  "account": "123456789012",
  "time": "2020-11-10T23:41:44Z",
  "region": "eu-west-1",
  "resources": [
    "arn:aws:geo:eu-west-1:0123456789101:tracker/Tracker_EXAMPLE"
  ],
  "detail": {
    "EventType": "UPDATE",
    "TrackerName": "tracker_2",
    "DeviceId": "Device1-EXAMPLE",
    "SampleTime": "2020-11-10T23:41:43.826Z",
    "ReceivedTime": "2020-11-10T23:41:39.235Z",
    "Position": [
      -123.08569321875426,
      49.23766166742559
    ],
    "Accuracy": {
      "Horizontal": 15.3
    },
    "PositionProperties": {
      "ExampleKey1": "ExampleField1",
      "ExampleKey2": "ExampleField2"
    }
  }
}
```

# Track with AWS IoT, MQTT, with Amazon Location Service
Track with AWS IoT and MQTT

[MQTT](http://mqtt.org/) is a lightweight and widely adopted messaging protocol designed for constrained devices. AWS IoT Core supports device connections that use the MQTT protocol and MQTT over WebSocket Secure (WSS) protocol. 

[AWS IoT Core](https://aws.amazon.com/iot-core/) connects devices to AWS and enables you to send and receive messages between them. The AWS IoT Core rules engine stores queries about your devices' message topics and enables you to define actions for sending messages to other AWS services, such as Amazon Location Service. Devices that are aware of their location as coordinates can have their locations forwarded to Amazon Location through the rules engine.

**Note**  
Devices may know their own position, for example via built-in GPS. AWS IoT also has support for third party device location tracking. For more information, see [AWS IoT Core Device Location](https://docs.aws.amazon.com/iot/latest/developerguide/device-location.html) in the *AWS IoT Core Developer Guide*.

The following walkthrough describes tracking using AWS IoT Core rules. You can also send the device information to your own AWS Lambda function, if you need to process it before sending to Amazon Location. For more details about using Lambda to process your device locations, see [Tutorial: Use AWS Lambda with MQTT](tracking-using-mqtt-with-lambda.md).

**Topics**
+ [

## Prerequisites
](#mqtt-prerequisite)
+ [

## Create an AWS IoT Core rule
](#mqtt-create-iot-rule)
+ [

## Tutorial: Test your AWS IoT Core rule in the console
](#mqtt-test-iot-rule)
+ [

# Tutorial: Use AWS Lambda with MQTT
](tracking-using-mqtt-with-lambda.md)

## Prerequisites
Prerequisites

Before you can begin tracking, you must complete the following prerequisites:
+ [Create a tracker resource](start-tracking.md#start-create-tracker) that you will send the device location data to.
+ [Create an IAM role](https://docs.aws.amazon.com/iot/latest/developerguide/iot-create-role.html) for granting AWS IoT Core access to your tracker.

  When following those steps, use the following policy to give access to your tracker:

  ```
  {
    "Version": "2012-10-17",		 	 	 
    "Statement": [
      {
        "Sid": "WriteDevicePosition",
        "Effect": "Allow",
        "Action": "geo:BatchUpdateDevicePosition",
        "Resource": "arn:aws:geo:*:*:tracker/*"
      }
    ]
  }
  ```

## Create an AWS IoT Core rule


Next, create an AWS IoT Core rule to forward your devices' positional telemetry to Amazon Location Service. For more information about creating rules, see the following topics in the *AWS IoT Core Developer Guide*:
+ [Creating an AWS IoT rule](https://docs.aws.amazon.com/iot/latest/developerguide/iot-create-rule.html) for information about creating a new rule.
+ [Location action](https://docs.aws.amazon.com/iot/latest/developerguide/location-rule-action.html) for information specific to creating a rule for publishing to Amazon Location 

## Tutorial: Test your AWS IoT Core rule in the console
Tutorial: Test your AWS IoT Core rule

If no devices are currently publishing telemetry that includes location, you can test your rule using the AWS IoT Core console. The console has a test client where you can publish a sample message to verify the results of the solution.

1. Sign in to the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/home).

1. In the left navigation, expand **Test**, and choose **MQTT test client**.

1. Under **Publish to a topic**, set the **Topic name** to *iot/topic* (or the name of the topic that you set up in your AWS IoT Core rule, if different), and provide the following for the **Message payload**.

   ```
   {
     "payload": {
       "deviceid": "thing123",
       "timestamp": 1604940328,
       "location": { "lat": 49.2819, "long": -123.1187 },
       "accuracy": { "Horizontal": 20.5 },
       "positionProperties": { "field1": "value1", "field2": "value2" }
     }
   }
   ```

1. Choose **Publish** to topic to send the test message.

1. To validate that the message was received by Amazon Location Service, use the following AWS CLI command. If you modified it during setup, replace the tracker name with the one that you used.

   ```
   aws location batch-get-device-position --tracker-name MyTracker --device-ids thing123
   ```

# Tutorial: Use AWS Lambda with MQTT


While using AWS Lambda is no longer required when sending device location data to Amazon Location for tracking, you may still want to use Lambda in some cases. For example, if you wish to process your device location data yourself, before sending it on to Amazon Location. The following topics describe how to use Lambda to process messages before sending them to your tracker. For more information about this pattern, see the [reference architecture](https://d1.awsstatic.com/architecture-diagrams/ArchitectureDiagrams/amazon-location-service-ra.pdf).

**Topics**
+ [

## Prerequisites
](#mqtt-prerequisite-with-lambda)
+ [

## Create a Lambda function
](#mqtt-with-lambda-create-lambda)
+ [

## Create an AWS IoT Core rule
](#mqtt-create-iot-rule-with-lambda)
+ [

## Test your AWS IoT Core rule in the console
](#mqtt-test-iot-rule-with-lambda)

## Prerequisites
Prerequisites

Before you can begin tracking, you must [create a tracker resource](start-tracking.md). To create a tracker resource, you can use the Amazon Location console, the AWS CLI, or the Amazon Location APIs. 

The following example uses the Amazon Location Service console to create the tracker resource:

1. Open the Amazon Location Service console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. In the left navigation pane, choose **Trackers**. 

1.  Choose **Create tracker**. 

1. Fill out the following boxes:
   + **Name** – Enter a unique name that has a maximum of 100 characters. Valid entries include alphanumeric characters, hyphens, and underscores. For example, *MyTracker*.
   + **Description** – Enter an optional description. For example, *Tracker for storing AWS IoT Core device positions*.
   + **Position filtering** – Select the filtering that you want to use for position updates. For example, **Accuracy-based filtering**.

1. Choose **Create tracker**. 

## Create a Lambda function


To create a connection between AWS IoT Core and Amazon Location Service, you need an AWS Lambda function to process messages forwarded by AWS IoT Core. This function will extract any positional data, format it for Amazon Location Service, and submit it through the Amazon Location Tracker API. You can create this function through the AWS Lambda console, or you can use the AWS Command Line Interface (AWS CLI) or the AWS Lambda APIs. 

To create a Lambda function that publishes position updates to Amazon Location using the console:

1. Open the AWS Lambda console at [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/home).

1. From the left navigation, choose **Functions**. 

1.  Choose **Create Function**, and make sure that **Author from scratch** is selected. 

1. Fill out the following boxes:
   + **Function name** – Enter a unique name for your function. Valid entries include alphanumeric characters, hyphens, and underscores with no spaces. For example, *MyLambda*.
   + **Runtime** – Choose *Python 3.8*.

1. Choose **Create function**. 

1. Choose the **Code** tab to open the editor.

1. Overwrite the placeholder code in `lambda_function.py` with the following, replacing the value assigned to `TRACKER_NAME` with the name of the tracker that you created as a [prerequisite](#mqtt-prerequisite-with-lambda).

   ```
   from datetime import datetime
   import json
   import os
   
   import boto3
   
   # Update this to match the name of your Tracker resource
   TRACKER_NAME = "MyTracker"
   
   """
   This Lambda function receives a payload from AWS IoT Core and publishes device updates to 
   Amazon Location Service via the BatchUpdateDevicePosition API.
   
   Parameter 'event' is the payload delivered from AWS IoT Core.
   
   In this sample, we assume that the payload has a single top-level key 'payload' and a nested key
   'location' with keys 'lat' and 'long'. We also assume that the name of the device is nested in
   the payload as 'deviceid'. Finally, the timestamp of the payload is present as 'timestamp'. For
   example:
   
   >>> event
   { 'payload': { 'deviceid': 'thing123', 'timestamp': 1604940328,
     'location': { 'lat': 49.2819, 'long': -123.1187 },
     'accuracy': {'Horizontal': 20.5 },
     'positionProperties': {'field1':'value1','field2':'value2'} }
   }
   
   If your data doesn't match this schema, you can either use the AWS IoT Core rules engine to
   format the data before delivering it to this Lambda function, or you can modify the code below to
   match it.
   """
   def lambda_handler(event, context):
     update = {
         "DeviceId": event["payload"]["deviceid"],
         "SampleTime": datetime.fromtimestamp(event["payload"]["timestamp"]).strftime("%Y-%m-%dT%H:%M:%SZ"),
         "Position": [
           event["payload"]["location"]["long"],
           event["payload"]["location"]["lat"]
           ]
       }
     if "accuracy" in event["payload"]:
         update["Accuracy"] = event["payload"]['accuracy']
     if "positionProperties" in event["payload"]:
         update["PositionProperties"] = event["payload"]['positionProperties']
    
     client = boto3.client("location")
     response = client.batch_update_device_position(TrackerName=TRACKER_NAME, Updates=[update])
   
     return {
       "statusCode": 200,
       "body": json.dumps(response)
     }
   ```

1. Choose **Deploy** to save the updated function.

1. Choose the **Configuration** tab.

1. In the **Permissions** section, choose the hyperlinked Role name to grant Amazon Location Service permissions to your Lambda function.

1. From your role's **Summary** page, choose **Add permissions**, and then from the dropdown list, select **Create inline policy**.

1. Choose the **JSON** tab, and overwrite the policy with the following document. This allows your Lambda function to update device positions managed by all tracker resources across all Regions.

   ```
   {
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "WriteDevicePosition",
         "Effect": "Allow",
         "Action": "geo:BatchUpdateDevicePosition",
         "Resource": "arn:aws:geo:*:*:tracker/*"
       }
     ]
   }
   ```

1. Choose **Review policy**.

1. Enter a policy name. For example, *AmazonLocationTrackerWriteOnly*.

1. Choose **Create policy**.

You can modify this function code, as necessary, to adapt to your own device message schema.

## Create an AWS IoT Core rule


Next, create an AWS IoT Core rule to forward your devices' positional telemetry to the AWS Lambda function for transformation and publication to Amazon Location Service. The example rule provided assumes that any necessary transformation of device payloads is handled by your Lambda function. You can create this rule through the AWS IoT Core console, the AWS Command Line Interface (AWS CLI), or the AWS IoT Core APIs.

**Note**  
While the AWS IoT console handles the permission necessary to allow AWS IoT Core to invoke your Lambda function, if you are creating your rule from the AWS CLI or SDK, you must [configure a policy to grant permission to AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/lambda-rule-action.html#lambda-rule-action-requirements).

**To create an AWS IoT Core using the console**

1. Sign in to the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/home).

1. In the left navigation, expand **Act**, and choose **Rules**.

1. Choose **Create a rule** to start the new rule wizard.

1. Enter a name and description for your rule.

1. For the **Rule query statement**, update the `FROM` attribute to refer to a topic where at least one device is publishing telemetry that includes location. If you are testing the solution, no modification is needed.

   ```
   SELECT * FROM 'iot/topic'
   ```

1. Under **Set one or more actions **, choose **Add action**.

1. Select **Send a message to a lambda function**.

1. Choose **Configure action**.

1. Find and select your Lambda function from the list.

1. Choose **Add action**.

1. Choose **Create rule**.

## Test your AWS IoT Core rule in the console
Optional: Test your AWS IoT Core rule

If no devices are currently publishing telemetry that includes location, you can test your rule and this solution using the AWS IoT Core console. The console has a test client where you can publish a sample message to verify the results of the solution.

1. Sign in to the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/home).

1. In the left navigation, expand **Test**, and choose **MQTT test client**.

1. Under **Publish to a topic**, set the **Topic name** to *iot/topic* (or the name of the topic that you set up in your AWS IoT Core rule, if different), and provide the following for the **Message payload**. Replace the timestamp *1604940328* with a valid timestamp within the last 30 days (any timestamps older than 30 days are ignored).

   ```
   {
     "payload": {
       "deviceid": "thing123",
       "timestamp": 1604940328,
       "location": { "lat": 49.2819, "long": -123.1187 },
       "accuracy": { "Horizontal": 20.5 },
       "positionProperties": { "field1": "value1", "field2": "value2" }
     }
   }
   ```

1. Choose **Publish** to topic to send the test message.

1. To validate that the message was received by Amazon Location Service, use the following AWS CLI command. If you modified them during setup, replace the tracker name and device id with the ones that you used.

   ```
   aws location batch-get-device-position --tracker-name MyTracker --device-ids thing123
   ```

# Manage geofence collection resources with Amazon Location
Manage geofence resources

Manage your geofence collections using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

Review and complete the following tutorials to manage your geofence collection resounces.

**Topics**
+ [

# Tutorial: List your geofence collection resources
](viewing-geofence-collections.md)
+ [

# Tutorial: Get geofence collection details
](get-geofence-collection-details.md)
+ [

# Tutorial: Delete a geofence collection
](delete-geofence-collection.md)
+ [

# Tutorial: List stored geofences
](viewing-geofences.md)
+ [

# Tutorial: Get geofence details
](get-geofence-details.md)
+ [

# Tutorial: Delete geofences
](delete-geofence.md)

# Tutorial: List your geofence collection resources


You can view your geofence collection list using the Amazon Location console, the AWS CLI, or the Amazon Location APIs:

------
#### [ Console ]

**To view a list of geofence collections using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Geofence collections** from the left navigation pane.

1. View a list of your geofence collections under **My geofence collections**.

------
#### [ API ]

Use the `[ListGeofenceCollections](https://docs.aws.amazon.com/location/previous/APIReference/API_ListGeofenceCollections.html)` operation from the Amazon Location Geofences APIs. 

The following example is an API request to get a list of geofence collections in the AWS account. 

```
POST /geofencing/v0/list-collections
```

The following is an example response for `ListGeofenceCollections`:

```
{
    "Entries": [ 
    { 
        "CollectionName": "ExampleCollection",
        "CreateTime": 2020-09-30T22:59:34.142Z,
        "Description": "string",
        "UpdateTime": 2020-09-30T23:59:34.142Z
    },
    "NextToken": "1234-5678-9012"
}
```

------
#### [ CLI ]

Use the `[list-geofence-collections](https://docs.aws.amazon.com/cli/latest/reference/location/list-geofence-collections.html)` command.

The following example is an AWS CLI to get a list of geofence collections in the AWS account. 

```
aws location list-geofence-collections
```

------

# Tutorial: Get geofence collection details


You can get details about any geofence collection resource in your AWS account using the Amazon Location console, the AWS CLI, or the Amazon Location APIs:

------
#### [ Console ]

**To view the details of a geofence collection using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Geofence collections** from the left navigation pane.

1. Under **My geofence collections**, select the name link of the target geofence collection. 

------
#### [ API ]

Use the `[DescribeGeofenceCollection](https://docs.aws.amazon.com/location/previous/APIReference/API_DescribeGeofenceCollection.html)` operation from the Amazon Location Geofences APIs. 

The following example is an API request to get the geofence collection details for *ExampleCollection*.

```
GET /geofencing/v0/collections/ExampleCollection
```

The following is an example response for `DescribeGeofenceCollection`:

```
{
    "CollectionArn": "arn:aws:geo:us-west-2:123456789012:geofence-collection/GeofenceCollection",
    "CollectionName": "ExampleCollection",
    "CreateTime": 2020-09-30T22:59:34.142Z,
    "Description": "string",
    "KmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
    "Tags": { 
        "Tag1" : "Value1"
    },
    "UpdateTime": 2020-09-30T23:59:34.142Z
}
```

------
#### [ CLI ]

Use the `[describe-geofence-collection](https://docs.aws.amazon.com/cli/latest/reference/location/describe-geofence-collection.html)` command.

The following example is an AWS CLI to get the geofence collection details for *ExampleCollection*.

```
aws location describe-geofence-collection \
    --collection-name "ExampleCollection"
```

------

# Tutorial: Delete a geofence collection


You can delete a geofence collection from your AWS account using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To delete a geofence collection using the Amazon Location console**

**Warning**  
This operation deletes the resource permanently.

 

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Geofence collections** from the left navigation pane.

1. Under **My geofence collection**, select the target geofence collection.

1. Choose **Delete geofence collection**.

------
#### [ API ]

Use the `[DeleteGeofenceCollection](https://docs.aws.amazon.com/location/previous/APIReference/API_DeleteGeofenceCollection.html)` operation from the Amazon Location APIs. 

The following example is an API request to delete the geofence collection *ExampleCollection*.

```
DELETE /geofencing/v0/collections/ExampleCollection
```

The following is an example response for `DeleteGeofenceCollection`:

```
HTTP/1.1 200
```

------
#### [ CLI ]

Use the `[delete-geofence-collection](https://docs.aws.amazon.com/cli/latest/reference/location/delete-geofence-collection.html)` command.

The following example is an AWS CLI command to delete the geofence collection *ExampleCollection*.

```
aws location delete-geofence-collection \
    --collection-name "ExampleCollection"
```

------

# Tutorial: List stored geofences


You can list geofences stored in a specified geofence collection using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To view a list of geofences using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Geofence collections** from the left navigation pane.

1. Under **My geofence collection**, select the name link of the target geofence collection.

1. View geofences in the geofence collection under **Geofences**

------
#### [ API ]

Use the `[ListGeofences](https://docs.aws.amazon.com/location/previous/APIReference/API_ListGeofences.html)` operation from the Amazon Location Geofences APIs. 

The following example is an API request to get a list of geofences stored in the geofence collection *ExampleCollection*. 

```
POST /geofencing/v0/collections/ExampleCollection/list-geofences
```

The following is an example response for `ListGeofences`:

```
{
   "Entries": [ 
      { 
         "CreateTime": 2020-09-30T22:59:34.142Z,
         "GeofenceId": "geofence-1",
         "Geometry": { 
             "Polygon": [            
                 [-5.716667, -15.933333,
                 [-14.416667, -7.933333],
                 [-12.316667, -37.066667],
                 [-5.716667, -15.933333]
             ]
         },
         "Status": "ACTIVE",
         "UpdateTime": 2020-09-30T23:59:34.142Z
      }
   ],
   "NextToken": "1234-5678-9012"
}
```

------
#### [ CLI ]

Use the `[list-geofences](https://docs.aws.amazon.com/cli/latest/reference/location/list-geofences.html)` command.

The following example is an AWS CLI to get a list of geofences stored in the geofence collection *ExampleCollection*. 

```
aws location list-geofences \
    --collection-name "ExampleCollection"
```

------

# Tutorial: Get geofence details


You can get the details of a specific geofence, such as the create time, update time, geometry, and status, from a geofence collection using the Amazon Location console, AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To view the status of a geofence using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Geofence collections** from the left navigation pane.

1. Under **My geofence collection**, select the name link of the target geofence collection.

1. Under **Geofences**, you’ll be able to view the status of your geofences.

------
#### [ API ]

Use the `[GetGeofence](https://docs.aws.amazon.com/location/previous/APIReference/API_GetGeofence.html)` operation from the Amazon Location Geofences APIs. 

The following example is an API request to get the geofence details from a geofence collection *ExampleCollection*.

```
GET /geofencing/v0/collections/ExampleCollection/geofences/ExampleGeofence1
```

The following is an example response for `GetGeofence`:

```
{
   "CreateTime": 2020-09-30T22:59:34.142Z,
   "GeofenceId": "ExampleGeofence1",
   "Geometry": { 
      "Polygon": [            
          [-1,-1],
          [1,-1],
          [0,1],
          [-1,-1] 
      ]
   },
   "Status": "ACTIVE",
   "UpdateTime": 2020-09-30T23:59:34.142Z
}
```

------
#### [ CLI ]

Use the `[get-geofence](https://docs.aws.amazon.com/cli/latest/reference/location/get-geofence.html)` command.

The following example is an AWS CLI to get the geofence collection details for *ExampleCollection*.

```
aws location get-geofence \
    --collection-name "ExampleCollection" \
    --geofence-id "ExampleGeofence1"
```

------

# Tutorial: Delete geofences


You can delete geofences from a geofence collection using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To delete a geofence using the Amazon Location console**

**Warning**  
This operation deletes the resource permanently. 

 

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Geofence collections** from the left navigation pane.

1. Under **My geofence collection**, select the name link of the target geofence collection.

1. Under **Geofences**, select the target geofence.

1. Choose **Delete geofence**.

------
#### [ API ]

Use the `[BatchDeleteGeofence](https://docs.aws.amazon.com//location/previous/APIReference/API_BatchDeleteGeofence.html)` operation from the Amazon Location Geofences APIs. 

The following example is an API request to delete geofences from the geofence collection *ExampleCollection*.

```
POST /geofencing/v0/collections/ExampleCollection/delete-geofences
Content-type: application/json

{
   "GeofenceIds": [ "ExampleGeofence11" ]
}
```

The following is an example success response for `[BatchDeleteGeofence](https://docs.aws.amazon.com//location/previous/APIReference/API_BatchDeleteGeofence.html)`. 

```
HTTP/1.1 200
```

------
#### [ CLI ]

Use the `[batch-delete-geofence](https://docs.aws.amazon.com/cli/latest/reference/location/batch-delete-geofence.html)` command.

The following example is an AWS CLI command to delete geofences from the geofence collection *ExampleCollection*.

```
aws location batch-delete-geofence \
    --collection-name "ExampleCollection" \
    --geofence-ids "ExampleGeofence11"
```

------

# Manage tracker resources with Amazon Location
Manage tracker resources

You can manage your trackers using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

Review and complete the following tutorials to manage tracker resounces.

**Topics**
+ [

# Tutorial: List your trackers
](viewing-trackers.md)
+ [

# Tutorial: Disconnect a tracker from a geofence collection
](disassociate-tracker.md)
+ [

# Tutorial: Get tracker details with Amazon Location
](get-tracker-details.md)
+ [

# Tutorial: Delete a tracker with Amazon Location
](delete-tracker.md)

# Tutorial: List your trackers


You can view your trackers list using the Amazon Location console, the AWS CLI, or the Amazon Location APIs:

------
#### [ Console ]

**To view a list of existing trackers using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose** Trackers** from the left navigation.

1. View a list of your tracker resources under **My trackers**.

------
#### [ API ]

Use the `[ListTrackers](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_ListTrackers.html)` operation from the Amazon Location Trackers APIs. 

The following example is an API request to get a list of trackers in your AWS account. 

```
POST /tracking/v0/list-trackers
```

The following is an example response for `[ListTrackers](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_ListTrackers.html)`:

```
{
   "Entries": [ 
      { 
         "CreateTime": 2020-10-02T19:09:07.327Z,
         "Description": "string",
         "TrackerName": "ExampleTracker",
         "UpdateTime": 2020-10-02T19:10:07.327Z
      }
   ],
   "NextToken": "1234-5678-9012"
}
```

------
#### [ CLI ]

Use the `[list-trackers](https://docs.aws.amazon.com/cli/latest/reference/location/list-trackers.html)` command.

The following example is an AWS CLI to get a list of trackers in your AWS account. 

```
aws location list-trackers
```

------

# Tutorial: Disconnect a tracker from a geofence collection


You can disconnect a tracker from a geofence collection using the Amazon Location console, the AWS CLI, or the Amazon Location APIs:

------
#### [ Console ]

**To disassociate a tracker from an associated geofence collection using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Trackers** from the left navigation pane.

1. Under **My trackers**, select the name link of the target tracker.

1. Under **Linked Geofence Collections**, select a geofence collection with a **Linked** status.

1. Choose **Unlink**.

------
#### [ API ]

Use the `[DisassociateTrackerConsumer](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_DisassociateTrackerConsumer.html)` operation from the Amazon Location Trackers APIs. 

The following example is an API request to disassociate a tracker from an associated geofence collection. 

```
DELETE /tracking/v0/trackers/ExampleTracker/consumers/arn:aws:geo:us-west-2:123456789012:geofence-collection/ExampleCollection
```

The following is an example response for `[DisassociateTrackerConsumer](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_DisassociateTrackerConsumer.html)`: 

```
HTTP/1.1 200
```

------
#### [ CLI ]

Use the `[disassociate-tracker-consumer](https://docs.aws.amazon.com/cli/latest/reference/location/disassociate-tracker-consumer.html)` command.

The following example is an AWS CLI command to disassociate a tracker from an associated geofence collection. 

```
aws location disassociate-tracker-consumer \
    --consumer-arn "arn:aws:geo:us-west-2:123456789012:geofence-collection/ExampleCollection" \
    --tracker-name "ExampleTracker"
```

------

# Tutorial: Get tracker details with Amazon Location


You can get details about any tracker in your AWS account by using the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

------
#### [ Console ]

**To view tracker details by using the Amazon Location console**

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Trackers** from the left navigation.

1. Under **My trackers**, select the name link of the target tracker.

1. View the tracker details under **Information**.

------
#### [ API ]

Use the `[DescribeTracker](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_DescribeTracker.html)` operation from the Amazon Location Tracker APIs.

The following example is an API request to get the tracker details for *ExampleTracker*.

```
GET /tracking/v0/trackers/ExampleTracker
```

The following is an example response for `[DescribeTracker](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_DescribeTracker.html)`:

```
{
   "CreateTime": 2020-10-02T19:09:07.327Z,
   "Description": "string",
   "EventBridgeEnabled": false,
   "KmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
   "PositionFiltering": "TimeBased",
   "Tags": { 
      "Tag1" : "Value1" 
   },
   "TrackerArn": "arn:aws:geo:us-west-2:123456789012:tracker/ExampleTracker",
   "TrackerName": "ExampleTracker",
   "UpdateTime": 2020-10-02T19:10:07.327Z
}
```

------
#### [ CLI ]

Use the `[describe-tracker](https://docs.aws.amazon.com/cli/latest/reference/location/describe-tracker.html)` command.

The following example is an AWS CLI command to get tracker details for *ExampleTracker*.

```
aws location describe-tracker \
    --tracker-name "ExampleTracker"
```

------

# Tutorial: Delete a tracker with Amazon Location


You can delete a tracker from your AWS account using the Amazon Location console, the AWS CLI, or the Amazon Location APIs:

------
#### [ Console ]

**To delete an existing map resource using the Amazon Location console**

**Warning**  
This operation deletes the resource permanently. If the tracker resource is in use, you may encounter an error. Make sure that the target resource isn't a dependency for your applications. 

1. Open the Amazon Location console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/home).

1. Choose **Trackers** from the left navigation pane.

1. Under **My trackers**, select the target tracker.

1. Choose **Delete tracker**.

------
#### [ API ]

Use the `[DeleteTracker](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_DeleteTracker.html)` operation from the Amazon Location Tracker APIs. 

The following example is an API request to delete the tracker *ExampleTracker*.

```
DELETE /tracking/v0/trackers/ExampleTracker
```

The following is an example response for `[DeleteTracker](https://docs.aws.amazon.com/location-trackers/latest/APIReference/API_DeleteTracker.html)`: 

```
HTTP/1.1 200
```

------
#### [ CLI ]

Use the `[delete-tracker](https://docs.aws.amazon.com/cli/latest/reference/location/delete-tracker.html)` command.

The following example is an AWS CLI command to delete the tracker *ExampleTracker*.

```
aws location delete-tracker \
    --tracker-name "ExampleTracker"
```

------

# Sample Geofencing and Tracking mobile application


This topic covers tutorials designed to demonstrate the key features of using the Amazon Location geofences and trackers in a mobile application. The applications demonstrate how a tracker and geofence interact using a combination of Lambda, AWS IoT and Amazon Location features. There are two tutorials available.
+ [Sample tracking and geofencing application for Android](https://docs.aws.amazon.com//location/previous/developerguide/qs-android-tracking.html), and you can clone the project files from GitHub: [https://github.com/aws-geospatial/amazon-location-samples-android/tree/main/tracking-with-geofence-notifications](https://github.com/aws-geospatial/amazon-location-samples-android/tree/main/tracking-with-geofence-notifications).
+ [Sample tracking and geofencing application for iOS](https://docs.aws.amazon.com//location/previous/developerguide/qs-ios-tracking.html), and you can clone the project files from GitHub: [https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications](https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications).

# Sample tracking and geofence application for Android


This topic covers the Android tutorial designed to demonstrate the key features of using the Amazon Location geofences and trackers in a mobile application. The applications demonstrate how a tracker and geonfence interact using a combination of Lambda, AWS IoT and Amazon Location features.

**Topics**
+ [

# Tutorial: Create Amazon Location resources for your app
](qs-android-tracking-resources.md)
+ [

# Tutorial: Create a Geofence Collection
](qs-android-tracking-geofence.md)
+ [

# Tutorial: Link a tracker to a geofence collection
](qs-android-tracking-link-geofence.md)
+ [

# Tutorial: Use AWS Lambda with MQTT
](qs-android-tracking-lambda.md)
+ [

# Tutorial: Set up the sample app code
](qs-android-tracking-sample-app-code.md)
+ [

# Tutorial: Use the sample app
](qs-android-tracking-use.md)

# Tutorial: Create Amazon Location resources for your app


To begin you will need to create the required Amazon Location resources. These resources will be essential for the functionality of the application and executing the provided code snippets.

**Note**  
If you haven't created an AWS account, follow the instructions in the [AWS account managment](https://docs.aws.amazon.com/accounts/latest/reference/welcome-first-time-user.html) user guide.

To begin you will need to create a Amazon Cognito Identity Pool Id, use the following procedure:

1. Open the [Amazon Cognito console](https://console.aws.amazon.com/cognito/v2/) and select **Identity pools** from the left side menu, then select **Create Identity pool**. 

1. Make sure **Guest Access** is checked, and press **Next** to contiue.

1. Next create a new IAM role or Use an existing IAM role.

1. Enter an Identity pool name, and make sure Identity Pool has access to Amazon Location `(geo)`resources for the map and tracker you will be creating nin the next procedure.

Next you need to create and style a map in the AWS Amazon Location console, use the following procedure:

1. Navigate to the [Maps section](https://console.aws.amazon.com/location/maps/home) of the Amazon Location console and select **Create Map**.

1. Give the new map a **Name** and **Description**. Record the name you assign, as it is used later in the tutorial.

1. When choosing a map style, consider the map data provider. Refer to section 82 of the [AWS service terms](http://aws.amazon.com/service-terms) for more details.

1. Accept the [Amazon Location Terms and Conditions](https://aws.amazon.com/service-terms/#:~:text=82.%20Amazon%20Location%20Service), then select **Create Map**, to finish the map creation process.

Next you need to create a tracker in the Amazon Location console, use the following procedure:

1.  Open the [Maps section](https://console.aws.amazon.com/location/trackers) in the Amazon Location console.

1. Choose **Create tracker**.

1. Fill in the required fields. Make note of the tracker's **Name** as it will be refrenced throughout this tutoiral.

1. Under the **Position filtering** field, choose the option that best fits how you intend to use your tracker resource. If you do not set Position filtering, the default setting is `TimeBased`. For more information, see [Trackers](), and [PositionFiltering]() in the Amazon Location API Reference.

1.  Choose **Create tracker** to finish creating the tracker.

# Tutorial: Create a Geofence Collection


Now will you create a geofence collection. You can use either the console, API or CLI. The following procedures walk you through each option.
+ Create a geofence collection using the Amazon Location console:

  1.  Open the [Geofence Collections](https://console.aws.amazon.com/location/geofencing/home#/) section of the Amazon Location console.

  1. Choose **Create geofence collection**.

  1. Provide a name and description for the collection.

  1. Under the EventBridge rule with Amazon CloudWatch as a target, you can create an optional EventBridge rule to get started reacting to geofence events. This enables Amazon Location to publish events to Amazon CloudWatch Logs.

  1. Press the **Create geofence collection** to finish creating the collection.
+ Create a geofence collection using the Amazon Location API:

  Use the [CreateGeofenceCollection](https://docs.aws.amazon.com/location/previous/APIReference/API_CreateGeofenceCollection.html) operation from the Amazon Location Geofences APIs. The following example uses an API request to create a geofence collection called `GEOCOLLECTION_NAME`.

  ```
  POST /geofencing/v0/collections
  Content-type: application/json
  
  {
     "CollectionName": "GEOCOLLECTION_NAME",
     "Description": "Geofence collection 1 for shopping center",
     "Tags": { 
        "Tag1" : "Value1"
     }
  }
  ```
+ Create a geofence collection using AWS CLI commands:

  Use the `create-geofence-collection` command. The following example uses an AWS CLI to create a geofence collection called `GEOCOLLECTION_NAME`. For more information on using the AWS CLI, see the [AWS Command Line Interface Documentation](https://docs.aws.amazon.com/cli/).

  ```
  aws location \
    create-geofence-collection \
    --collection-name "ExampleGeofenceCollection" \
    --description "Shopping center geofence collection" \
    --tags Tag1=Value1
  ```

# Tutorial: Link a tracker to a geofence collection


To link a tracker to a geofence collection you can use either the console, API, or CLI. The following procedures walk you through each option.

Link a tracker resource to a geofence collection using the Amazon Location Service console:

1.  Open the Amazon Location console.

1.  In the left navigation pane, choose **Trackers**.

1.  Under **Device Trackers**, select the name link of the target tracker.

1.  Under **Linked Geofence Collections**, choose **Link Geofence Collection**.

1.  In the **Linked Geofence Collection window**, select a geofence collection from the dropdown menu.

1.  Choose **Link**.

1.  After you link the tracker resource, it will be assigned an Active status.

Link a tracker resource to a geofence collection using the Amazon Location APIs:

Use the `AsssociateTrackerConsumer` operation from the Amazon Location Trackers APIs. The following example uses an API request that associates an `ExampleTracker` with a geofence collection using its Amazon Resource Name (ARN).

```
        POST /tracking/v0/trackers/ExampleTracker/consumers
        Content-type: application/json
        {
           "ConsumerArn": "arn:aws:geo:us-west-2:123456789012:geofence-collection/GOECOLLECTION_NAME"
            }
```

Link a tracker resource to a geofence collection using AWS CLI commands:

Use the `associate-tracker-consumer ` command. The following example uses an AWS CLI to create a geofence collection called `GOECOLLECTION_NAME`.

```
aws location \
associate-tracker-consumer \
    --consumer-arn "arn:aws:geo:us-west-2:123456789012:geofence-collection/GOECOLLECTION_NAME" \
    --tracker-name "ExampleTracker"
```

# Tutorial: Use AWS Lambda with MQTT


In order to create a connection between AWS IoT and Amazon Location, you need a Lambda function to process messages forwarded by EventBridge CloudWatch events. This function will extract any positional data, format it for Amazon Location, and submit it through the Amazon Location Tracker API.

The following procedure shows you how to create this function through the Lambda console:

1. Open the [console](https://console.aws.amazon.com/lambda/).

1. From the left navigation, choose **Functions**.

1. Then choose **Create Function**, and make sure that the **Author from scratch** option is selected.

1.  provide a **Function name**, and for the **Runtime** option, choose Node.js 16.x.

1. Choose **Create function**.

1. Open the **Code tab** to access the editor.

1. Overwrite the placeholder code in the `index.js` file with the following:

   ```
               const AWS = require('aws-sdk')
               const iot = new AWS.Iot();
               exports.handler =  function(event) {
                 console.log("event===>>>", JSON.stringify(event));
                 var param = {
                   endpointType: "iot:Data-ATS"
                 };
                 iot.describeEndpoint(param, function(err, data) {
                   if (err) {
                     console.log("error===>>>", err, err.stack); // an error occurred
                   } else {
                     var endp = data['endpointAddress'];
                     const iotdata = new AWS.IotData({endpoint: endp});    
                     const trackerEvent = event["detail"]["EventType"];
                     const src = event["source"];
                     const time = event["time"];
                     const gfId = event["detail"]["GeofenceId"];
                     const resources = event["resources"][0];  
                     const splitResources = resources.split(".");  
                     const geofenceCollection = splitResources[splitResources.length - 1];
                     const coordinates = event["detail"]["Position"];                               
                     const deviceId = event["detail"]["DeviceId"]; 
                     console.log("deviceId===>>>", deviceId);
                     const msg =  {
                         "trackerEventType" : trackerEvent,
                         "source" : src,
                         "eventTime" : time,
                         "geofenceId" : gfId,
                         "coordinates": coordinates, 
                         "geofenceCollection": geofenceCollection
                       };
                     const params = {
                       topic: `${deviceId}/tracker`,
                       payload: JSON.stringify(msg),
                       qos: 0
                     };
                     iotdata.publish(params, function(err, data) {
                         if (err) {
                           console.log("error===>>>", err, err.stack); // an error occurred
                         } else {
                           console.log("Ladmbda triggered===>>>", trackerEvent);  // successful response 
                         }
                     }); 
                   }
                 });
               }
   ```

1. Press the **Deploy** to save the updated function.

1. Next open the **Configuration** tab.

1. In the **Triggers** section, press the **Add Trigger** button.

1. Select **EventBridge (CloudWatch Events)** in Source field.

1. Select the **Existing Rules** option.

1. Enter the rule name, for example `AmazonLocationMonitor-GEOFENCECOLLECTION_NAME`.

1. Press the **Add** button.

1.  This will also attach **Resource-based policy statements** in the permissions tab

Now you will set up the MQTT Test Client using AWS IoT, use the following procedure:

1. Open the [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

1.  In the left navigation pane, select the **MQTT test client**.

1.  You'll see a section titled **MQTT test client** where you can configure your MQTT connection.

1.  After configuring the necessary settings, click on the **Connect** button to establish a connection to the MQTT broker using the provided parameters.

1.  Record endpoint, as it is used later in the tutoiral.

   Once connected to the test client, you can subscribe to MQTT topics or publish messages to topics using the respective input fields provided in the MQTT test client interface. Next you will create an AWS IoT policy.

1.  On the left side menu, under **Manage** expand **Security** option and click on **Policies**.

1.  Click on **Create Policy** button.

1.  Enter a policy name.

1.  On **Policy Document** select **JSON** tab.

1. Copy paste the policy shown below, but make sure to update all elements with your `REGION` and `ACCOUNT_ID`:

   ```
   {
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Action": [
           "iot:Connect",
           "iot:Publish",
           "iot:Subscribe",
           "iot:Receive"
         ],
         "Resource": [
           "arn:aws:iot:REGION:ACCOUNT_ID:client/${cognito-identity.amazonaws.com:sub}",
           "arn:aws:iot:REGION:ACCOUNT_ID:topic/${cognito-identity.amazonaws.com:sub}",
           "arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/${cognito-identity.amazonaws.com:sub}/*",
           "arn:aws:iot:REGION:ACCOUNT_ID:topic/${cognito-identity.amazonaws.com:sub}/tracker"
         ],
         "Effect": "Allow"
       }
     ]
   }
   ```

1. Select the **Create** button to finish.

After completing the previous procedure, you will now update the permissions for the guest role as follows:

1. Navigate to Amazon Cognito and open your identity pool. Then, proceed to user access and select the guest role.

1. Click on permission policies to enable editing.

   ```
   {
       'Version': '2012-10-17		 	 	 ',
       'Statement': [
           {
               'Action': [
                   'geo:GetMap*',
                   'geo:BatchUpdateDevicePosition',
                   'geo:BatchEvaluateGeofences',
                   'iot:Subscribe',
                   'iot:Publish',
                   'iot:Connect',
                   'iot:Receive',
                   'iot:AttachPrincipalPolicy',
                   'iot:AttachPolicy',
                   'iot:DetachPrincipalPolicy',
                   'iot:DetachPolicy'
               ],
               'Resource': [
                   'arn:aws:geo:us-east-1:{USER_ID}:map/{MAP_NAME}',
                   'arn:aws:geo:us-east-1:{USER_ID}:tracker/{TRACKER_NAME}',
                   'arn:aws:geo:us-east-1:{USER_ID}:geofence-collection/{GEOFENCE_COLLECTION_NAME}',
                   'arn:aws:iot:us-east-1:{USER_ID}:client/${cognito-identity.amazonaws.com:sub}',
                   'arn:aws:iot:us-east-1:{USER_ID}:topic/${cognito-identity.amazonaws.com:sub}',
                   'arn:aws:iot:us-east-1:{USER_ID}:topicfilter/${cognito-identity.amazonaws.com:sub}/*',
                   'arn:aws:iot:us-east-1:{USER_ID}:topic/${cognito-identity.amazonaws.com:sub}/tracker'
               ],
               'Effect': 'Allow'
           },
           {
               'Condition': {
                   'StringEquals': {
                       'cognito-identity.amazonaws.com:sub': '${cognito-identity.amazonaws.com:sub}'
                   }
               },
               'Action': [
                   'iot:AttachPolicy',
                   'iot:DetachPolicy',
                   'iot:AttachPrincipalPolicy',
                   'iot:DetachPrincipalPolicy'
               ],
               'Resource': [
                   '*'
               ],
               'Effect': 'Allow'
           }
       ]
   }
   ```

1. With the above policy changes, all necessary AWS resources are now configured appropriately for the application.

# Tutorial: Set up the sample app code


This page provides a sample Android application code that demonstrates how to integrate the tracking capabilities of Amazon Location Service into your mobile applications. 

1. Clone this repository: [https://github.com/aws-geospatial/amazon-location-samples-android/tree/main/tracking-with-geofence-notifications](https://github.com/aws-geospatial/amazon-location-samples-android/tree/main/tracking-with-geofence-notifications) to your local machine.

1. Open the `AmazonSampleSDKApp` project in Android Studio.

1. Build and run the app on your Android device or emulator.

# Tutorial: Use the sample app


This guide walks you through the process of setting up and using the sample Android tracking application. By following the step-by-step instructions outlined in this section, you'll learn how to configure the necessary AWS resources, integrate the tracking functionality into the sample app, and deploy it to your Android device. 

To use the sample follow these procedures:
+ **Create a `custom.properties`**:

  To configure your `custom.properties` file, follow these steps:

  1. Open your preferred text editor or IDE.

  1. Create a new file.

  1. Save the file with the name `custom.properties`.

  1. Update the `custom.properties` with the following code sample, and replace the `MQTT_END_POINT`, `POLICY_NAME`, `GEOFENCE_COLLECTION_NAME`, and `TOPIC_TRACKER` with your resoucre names:

     ```
     MQTT_END_POINT=YOUR_END_POINT.us-east-1.amazonaws.com
     POLICY_NAME=YOUR_POLICY
     GEOFENCE_COLLECTION_NAME=YOUR_GEOFENCE
     TOPIC_TRACKER=YOUR_TRACKER
     ```

  1. Clean and Rebuild the project. After this, you can run the project.
+ **Sign In**:

  To sign in to the application, follow the below steps:

  1. Press the **Sign In** button.

  1. Provide an **Identity Pool Id**, **Tracker name**, and a **Map name**.

  1. Press **Sign In** again to finish.
+ **Manage Filters**:

  Open the configuration screen, and perform the following:

  1. Toggle filters on or off using the switch UI.

  1. Update Time and Distance filters when needed.
+ **Tracking Operations:**

  Open the tracking screen and perform the following:
  + You can start and stop tracking in foreground, background, or in battery-saver mode by pressing the respective buttons.

# Sample tracking and geofencing application for iOS


This topic covers the iOS tutorial designed to demonstrate the key features of using the Amazon Location geofences and trackers in a mobile application. The applications demonstrate how a tracker and geonfence interact using a combination of Lambda, AWS IoT and Amazon Location features.

**Topics**
+ [

# Tutorial: Create Amazon Location resources for your app
](qs-ios-tracking-resources.md)
+ [

# Tutorial: Create a Geofence Collection
](qs-ios-tracking-geofence.md)
+ [

# Tutorial: Link a tracker to a geofence collection
](qs-ios-tracking-link-geofence.md)
+ [

# Tutorial: Use AWS Lambda with MQTT
](qs-ios-tracking-lambda.md)
+ [

# Tutorial: Set up sample app code
](qs-ios-tracking-setup-sample.md)
+ [

# Tutorial: Use the sample app
](qs-ios-tracking-usage.md)

# Tutorial: Create Amazon Location resources for your app


To begin you will need to create the required Amazon Location resources. These resources will be essential for the functionality of the application and executing the provided code snippets.

**Note**  
If you haven't created an AWS account, follow the instructions in the [AWS account managment](https://docs.aws.amazon.com/accounts/latest/reference/welcome-first-time-user.html) user guide.

To begin you will need to create a Amazon Cognito Identity Pool Id, use the following procedure:

1. Open the [Amazon Cognito console](https://console.aws.amazon.com/cognito/v2/) and select **Identity pools** from the left side menu, then select **Create Identity pool**. 

1. Make sure **Guest Access** is checked, and press **Next** to contiue.

1. Next create a new IAM role or Use an existing IAM role.

1. Enter an Identity pool name, and make sure Identity Pool has access to Amazon Location `(geo)`resources for the map and tracker you will be creating nin the next procedure.

Next you need to create and style a map in the AWS Amazon Location console, use the following procedure:

1. Navigate to the [Maps section](https://console.aws.amazon.com/location/maps/home) of the Amazon Location console and select **Create Map**.

1. Give the new map a **Name** and **Description**. Record the name you assign, as it is used later in the tutorial.

1. When choosing a map style, consider the map data provider. Refer to section 82 of the [AWS service terms](http://aws.amazon.com/service-terms) for more details.

1. Accept the [Amazon Location Terms and Conditions](https://aws.amazon.com/service-terms/#:~:text=82.%20Amazon%20Location%20Service), then select **Create Map**, to finish the map creation process.

Next you need to create a tracker in the Amazon Location console, use the following procedure:

1.  Open the [Maps section](https://console.aws.amazon.com/location/trackers) in the Amazon Location console.

1. Choose **Create tracker**.

1. Fill in the required fields. Make note of the tracker's **Name** as it will be refrenced throughout this tutoiral.

1. Under the **Position filtering** field, choose the option that best fits how you intend to use your tracker resource. If you do not set Position filtering, the default setting is `TimeBased`. For more information, see [Start tracking](location/previous/developerguide/start-tracking.html), and start-tracking.html [PositionFiltering](https://docs.aws.amazon.com/location/previous/APIReference/API_BatchUpdateDevicePosition.html) in the Amazon Location API Reference.

1.  Choose **Create tracker** to finish creating the tracker.

# Tutorial: Create a Geofence Collection


Now will you create a geofence collection. You can use either the console, API or CLI. The following procedures walk you through each option.
+ Create a geofence collection using the Amazon Location console:

  1.  Open the [Geofence Collections](https://console.aws.amazon.com/location/geofencing/home#/) section of the Amazon Location console.

  1. Choose **Create geofence collection**.

  1. Provide a name and description for the collection.

  1. Under the EventBridge rule with Amazon CloudWatch as a target, you can create an optional EventBridge rule to get started reacting to geofence events. This enables Amazon Location to publish events to Amazon CloudWatch Logs.

  1. Press the **Create geofence collection** to finish creating the collection.
+ Create a geofence collection using the Amazon Location API:

  Use the [CreateGeofenceCollection](https://docs.aws.amazon.com/location/previous/APIReference/API_CreateGeofenceCollection.html) operation from the Amazon Location Geofences APIs. The following example uses an API request to create a geofence collection called `GEOCOLLECTION_NAME`.

  ```
  POST /geofencing/v0/collections
  Content-type: application/json
  
  {
     "CollectionName": "GEOCOLLECTION_NAME",
     "Description": "Geofence collection 1 for shopping center",
     "Tags": { 
        "Tag1" : "Value1"
     }
  }
  ```
+ Create a geofence collection using AWS CLI commands:

  Use the `create-geofence-collection` command. The following example uses an AWS CLI to create a geofence collection called `GEOCOLLECTION_NAME`. For more information on using the AWS CLI, see the [AWS Command Line Interface Documentation](https://docs.aws.amazon.com/cli/).

  ```
  aws location \
    create-geofence-collection \
    --collection-name "ExampleGeofenceCollection" \
    --description "Shopping center geofence collection" \
    --tags Tag1=Value1
  ```

# Tutorial: Link a tracker to a geofence collection


To link a tracker to a geofence collection you can use either the console, API, or CLI. The following procedures walk you through each option.

Link a tracker resource to a geofence collection using the Amazon Location Service console:

1.  Open the Amazon Location console.

1.  In the left navigation pane, choose **Trackers**.

1.  Under **Device Trackers**, select the name link of the target tracker.

1.  Under **Linked Geofence Collections**, choose **Link Geofence Collection**.

1.  In the **Linked Geofence Collection window**, select a geofence collection from the dropdown menu.

1.  Choose **Link**.

1.  After you link the tracker resource, it will be assigned an Active status.

Link a tracker resource to a geofence collection using the Amazon Location APIs:

Use the `AsssociateTrackerConsumer` operation from the Amazon Location Trackers APIs. The following example uses an API request that associates ExampleTracker with a geofence collection using its Amazon Resource Name (ARN).

```
POST /tracking/v0/trackers/ExampleTracker/consumers
Content-type: application/json
    {
       "ConsumerArn": "arn:aws:geo:us-west-2:123456789012:geofence-collection/GEOCOLLECTION_NAME"
    }
```

Llink a tracker resource to a geofence collection using AWS CLI commands:

Use the `associate-tracker-consumer ` command. The following example uses an AWS CLI to create a geofence collection called `GEOCOLLECTION_NAME`.

```
aws location \
    associate-tracker-consumer \
        --consumer-arn "arn:aws:geo:us-west-2:123456789012:geofence-collection/GEOCOLLECTION_NAME" \
        --tracker-name "ExampleTracker"
```

# Tutorial: Use AWS Lambda with MQTT


In order to create a connection between AWS IoT and Amazon Location, you need a Lambda function to process messages forwarded by EventBridge CloudWatch events. This function will extract any positional data, format it for Amazon Location, and submit it through the Amazon Location Tracker API.

The following procedure shows you how to create this function through the Lambda console:

1. Open the [console](https://console.aws.amazon.com/lambda/).

1. From the left navigation, choose **Functions**.

1. Then choose **Create Function**, and make sure that the **Author from scratch** option is selected.

1.  provide a **Function name**, and for the **Runtime** option, choose Node.js 16.x.

1. Choose **Create function**.

1. Open the **Code tab** to access the editor.

1. Overwrite the placeholder code in the `index.js` file with the following:

   ```
               const AWS = require('aws-sdk')
               const iot = new AWS.Iot();
               exports.handler =  function(event) {
                 console.log("event===>>>", JSON.stringify(event));
                 var param = {
                   endpointType: "iot:Data-ATS"
                 };
                 iot.describeEndpoint(param, function(err, data) {
                   if (err) {
                     console.log("error===>>>", err, err.stack); // an error occurred
                   } else {
                     var endp = data['endpointAddress'];
                     const iotdata = new AWS.IotData({endpoint: endp});    
                     const trackerEvent = event["detail"]["EventType"];
                     const src = event["source"];
                     const time = event["time"];
                     const gfId = event["detail"]["GeofenceId"];
                     const resources = event["resources"][0];  
                     const splitResources = resources.split(".");  
                     const geofenceCollection = splitResources[splitResources.length - 1];
                     const coordinates = event["detail"]["Position"];                               
                     const deviceId = event["detail"]["DeviceId"]; 
                     console.log("deviceId===>>>", deviceId);
                     const msg =  {
                         "trackerEventType" : trackerEvent,
                         "source" : src,
                         "eventTime" : time,
                         "geofenceId" : gfId,
                         "coordinates": coordinates, 
                         "geofenceCollection": geofenceCollection
                       };
                     const params = {
                       topic: `${deviceId}/tracker`,
                       payload: JSON.stringify(msg),
                       qos: 0
                     };
                     iotdata.publish(params, function(err, data) {
                         if (err) {
                           console.log("error===>>>", err, err.stack); // an error occurred
                         } else {
                           console.log("Ladmbda triggered===>>>", trackerEvent);  // successful response 
                         }
                     }); 
                   }
                 });
               }
   ```

1. Press the **Deploy** to save the updated function.

1. Next open the **Configuration** tab.

1. In the **Triggers** section, press the **Add Trigger** button.

1. Select **EventBridge (CloudWatch Events)** in Source field.

1. Select the **Existing Rules** option.

1. Enter the rule name, for example `AmazonLocationMonitor-GEOFENCECOLLECTION_NAME`.

1. Press the **Add** button.

1.  This will also attach **Resource-based policy statements** in the permissions tab

Now you will set up the AWS IoT MQTT Test Client, use the following procedure:

1. Open the [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

1.  In the left navigation pane, select the **MQTT test client**.

1.  You'll see a section titled **MQTT test client** where you can configure your MQTT connection.

1.  After configuring the necessary settings, click on the **Connect** button to establish a connection to the MQTT broker using the provided parameters.

1.  Record endpoint, as it is used later in the tutoiral.

   Once connected to the test client, you can subscribe to MQTT topics or publish messages to topics using the respective input fields provided in the MQTT test client interface. Next you will create an AWS IoT policy.

1.  On the left side menu, under **Manage** expand **Security** option and click on **Policies**.

1.  Click on **Create Policy** button.

1.  Enter a policy name.

1.  On **Policy Document** select **JSON** tab.

1. Copy paste the policy shown below, but make sure to update all elements with your `REGION` and `ACCOUNT_ID`:

   ```
   {
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Action": [
           "iot:Connect",
           "iot:Publish",
           "iot:Subscribe",
           "iot:Receive"
         ],
         "Resource": [
           "arn:aws:iot:REGION:ACCOUNT_ID:client/${cognito-identity.amazonaws.com:sub}",
           "arn:aws:iot:REGION:ACCOUNT_ID:topic/${cognito-identity.amazonaws.com:sub}",
           "arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/${cognito-identity.amazonaws.com:sub}/*",
           "arn:aws:iot:REGION:ACCOUNT_ID:topic/${cognito-identity.amazonaws.com:sub}/tracker"
         ],
         "Effect": "Allow"
       }
     ]
   }
   ```

1. Select the **Create** button to finish.

# Tutorial: Set up sample app code


In order to setup the sample code you must have the following tools installed:
+ Git
+ XCode 15.3 or Later
+ iOS Simulator 16 or later

Use this procedure to set up the sample app code:

1. Clone the git repository from this URL: [https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications](https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications).

1.  Open the `AWSLocationSampleApp.xcodeproj` project file.

1.  Wait for the package resolution process to finish.

1. On the project navigation menu rename `ConfigTemplate.xcconfig` to `Config.xcconfig` and fill in the following values:

   ```
   IDENTITY_POOL_ID = `YOUR_IDENTITY_POOL_ID`
   MAP_NAME = `YOUR_MAP_NAME`
   TRACKER_NAME = `YOUR_TRACKER_NAME`
   WEBSOCKET_URL = `YOUR_MQTT_TEST_CLIENT_ENDPOINT`
   GEOFENCE_ARN = `YOUR_GEOFENCE_COLLECTION_NAME`
   ```

# Tutorial: Use the sample app


After setting up the sample code you can now run the app on an iOS simulator or a physical device.

1. Build and run the app.

1. The app will ask you for location and notification permissions. You need to allow them.

1. Press the **Cognito Configuration** button.

1. Save the configuration.

1. You can now see the Filter options for time, distance and accuracy. Use them as per your need.

1. Go to **Tracking** tab in the app and you will see the map and **Start Tracking** button.

1. If you have installed the app on a simulator you may want to simulate location changes. This can be done in **Features** under the **Location** menu option. For example select **Features**, then **Location**, then **Freeway Drive**.

1. Press the **Start Tracking** button. You should see the tracking points on the map.

1. The app is also tracking the locations in the background. So, when you move the app in the background it will ask for your permission to continue tracking in background mode.

1. You can stop the tracking by tapping on **Stop Tracking** button.