

# Get started as a developer using Amazon Location Service
<a name="dev-overview"></a>

You can use Amazon Location Service to provide geographic-related functionality for apps across many different form factors and systems, including backend web services, web applications, and mobile applications. There are many tools provided to help you build your applications, including SDKs, libraries, and sample code.

This section provides information and links to help you get started with Amazon Location. In particular, the following topics provide information that can be most helpful to you:
+ [Scenarios and use cases](dev-usecases.md) – A list of development scenarios and how Amazon Location Service can help you complete them.
+ [Amazon Location SDKs and tools](dev-sdks.md) – The software development kits (SDKs) and libraries that will help you when programming with Amazon Location.
+ [Amazon Location Service API Reference](https://docs.aws.amazon.com/location/previous/APIReference/welcome.html) – A reference to the core Amazon Location APIs that ship with the AWS SDK.
+ [Code examples](samples.md) – This section provides samples that will help you get started or to add functionality to your existing application.
+ [Quick start tutorial](getting-started.md) – This tutorial shows you how to create your first application. There are versions of the tutorial for creating a web application or an Android-based mobile application.
+ [Amazon Location Service concepts](how-it-works.md) – This section of this guide describes the basic concepts of Amazon Location, including sections on Maps, Places search, Routes, and Geofences and Trackers.
+ [Amplify](https://aws.amazon.com/amplify/) – Amplify is a complete solution that encapsulates much of the functionality needed for creating web and mobile applications using the AWS Cloud. If you are already using Amplify, or choose to use Amplify, it has a geo library using Amazon Location Service built-in that you can use. To get started with Amplify Geo, see the documentation [here](https://docs.amplify.aws/lib/geo/getting-started/q/platform/js/).

# Scenarios and use cases
<a name="dev-usecases"></a>

Amazon Location Service is a service that runs in the AWS Cloud. You may call it from your own Amazon EC2 instances in the cloud, but many mapping applications will run on devices, or a combination of devices and the cloud. The following lists just a few typical scenarios and how you might approach developing them.
+ A backend application that helps you to optimize routes for drivers in your fleet.

  You can write an application that runs on [Amazon EC2](https://docs.aws.amazon.com/ec2/) in the AWS Cloud that uses the Amazon Location Service to [calculate route matrices](calculate-route-matrix.md) as an input to a route optimizer for your fleet. Use the [AWS SDK](location-actions.md#sdk-general-information-section) to make calls to Amazon Location.
+ A web application that allows your customers to find the locations of your business.

  You can create a website that runs on Amazon EC2 instances, including a location-based application. Use the [AWS SDK for JavaScript](location-actions.md#sdk-general-information-section) to develop a web application to look up locations using [places search](searching-for-places.md), and display results on a [map](using-maps.md) using MapLibre. Use the Amazon Location SDK to make programming with location easier.
+ Add location features to an existing iOS or Android application.

  You can use the AWS SDK for Swift (iOS) or [Kotlin](https://docs.aws.amazon.com/sdk-for-kotlin) (Android) to make calls to Amazon Location to add [places search](searching-for-places.md) and [maps](using-maps.md) functionality to your application. Use MapLibre to render maps. There are additional [AWS SDKs](location-actions.md#sdk-general-information-section) available for other languages.
+ Track assets (devices or vehicles), and get updates when they are enter or exit areas that you define.

  An application to track devices consists of several parts.
  + Each device that you are tracking must have a [tracker](start-tracking.md) resource created to track it. It must send position updates to Amazon Location Service, for example, by using [MQTT](tracking-using-mqtt.md).
  + Create [geofences](add-geofences.md) to define areas that you want to get enter and exit events for your assets.
  + You can use [Amazon EC2](https://docs.aws.amazon.com/ec2/) or [AWS Lambda](https://docs.aws.amazon.com/lambda/) to respond to your events as assets enter or exit the geofence areas.
  + You can expand upon this to create web or device applications to track and display your asset locations on maps.

The following section gives details on tools and libraries available to use with each aspect of the Amazon Location Service.

# SDKs and tools for using Amazon Location Service
<a name="dev-sdks"></a>

AWS provides Software Development Kits (SDKs) for multiple programming languages, allowing you to easily integrate the Amazon Location Service into your applications. This page outlines the available SDKs, their installation procedures, and code examples to help you get started with the Amazon Location Service in your preferred development environment.

There are several tools that will help you to use Amazon Location Service.
+ **AWS SDKs** – The AWS software development kits (SDKs) are available in many popular programming languages, providing an API, code examples, and documentation that makes it easier to build applications in your preferred language. The AWS SDKs include the core Amazon Location APIs and functionality, including access to Maps, Places search, Routes, Geofence, and Trackers. To learn more about the SDKs available to use with Amazon Location Service for different applications and languages, see [SDKs by language](dev-by-language.md).
+ **MapLibre** – Amazon Location Service recommends rendering maps using the [MapLibre](https://github.com/maplibre/maplibre-gl-js) rendering engine. MapLibre is an engine for displaying maps in web or mobile applications. MapLibre also has a plugin model, and supports user interface for searching and routes in some languages and platforms. To learn more about using MapLibre and the functionality it provides, see [How to use MapLibre](dev-maplibre.md).
+ **Amazon Location SDK** – The Amazon Location SDK is a set of open source libraries that make it easier to develop applications with Amazon Location Service. The libraries provide functionality to support authentication for mobile and web applications, location tracking for mobile applications, conversion between Amazon Location data types and [GeoJSON](https://geojson.org/), as well as a hosted package of the Amazon Location client for the AWS SDK v3. To learn more about the Amazon Location SDK, see [How to use Amazon Location SDK](dev-location-libraries.md).
+ **Amazon Location Migration SDK** – The Amazon Location Migration SDK provides a bridge that allows you to migrate existing applications from Google Maps to Amazon Location. The Migration SDK provides an option for your application built using the Google Maps SDK for JavaScript to use Amazon Location Service without needing to rewrite any of the application or business logic if Amazon Location supports the capabilities used. The Migration SDK redirects all API calls to the Amazon Location instead of Google Map. To get started, see the [Amazon Location Migration SDK](https://github.com/aws-geospatial/amazon-location-migration) on GitHub.

# SDKs by language
<a name="dev-by-language"></a>

The following tables provide information about AWS SDKs and MapLibre versions for languages and frameworks, by application type: web, mobile, or backend application.

**SDK Versions**  
We recommend that you use the most recent build of the AWS SDK, and any other SDKs, that you use in your projects, and to keep the SDKs up to date. The AWS SDK provides you with the latest features and functionality, and also security updates. To find the latest build of the AWS SDK for JavaScript, for example, see the [browser installation ](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/index.html#In_the_Browser) topic in the *AWS SDK for JavaScript* documentation.

------
#### [ Web frontend ]

The following AWS SDKs and MapLibre versions are available for web frontend application development.


| Language / Framework | AWS SDK | Rendering Framework | 
| --- | --- | --- | 
|  **Fully supported**  | 
|  JavaScript  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  |  [https://github.com/maplibre/maplibre-gl-js](https://github.com/maplibre/maplibre-gl-js)  | 
|  ReactJS  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  |  [https://github.com/maplibre/maplibre-react-native](https://github.com/maplibre/maplibre-react-native)  | 
|  TypeScript  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  |  [https://github.com/maplibre/maplibre-gl-js](https://github.com/maplibre/maplibre-gl-js)  | 
|  **Partially supported**  | 
|  Flutter  |  [https://docs.amplify.aws/start/q/integration/flutter/](https://docs.amplify.aws/start/q/integration/flutter/) Flutter is not yet fully supported by AWS, but limited support is offered via Amplify.  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) The MapLibre Flutter library is considered experimental.  | 
|  Node.js  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  |   There is no MapLibre support for Node.js.  | 
|  PHP  |  [https://aws.amazon.com/sdk-for-php/](https://aws.amazon.com/sdk-for-php/)  |   There is no MapLibre support for PHP.  | 

------
#### [ Mobile frontend ]

The following AWS SDKs and MapLibre versions are available for mobile frontend application development.


| Language / Framework | AWS SDK | Rendering Framework | 
| --- | --- | --- | 
|  **Fully supported**  | 
|  Java  |  [https://aws.amazon.com/sdk-for-java/](https://aws.amazon.com/sdk-for-java/)  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native)  | 
|  Kotlin  |  [https://aws.amazon.com/sdk-for-kotlin/](https://aws.amazon.com/sdk-for-kotlin/)  Amazon Location Service Mobile Authentication SDK for Android: [https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-android](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-android) Amazon Location Service Mobile Tracking SDK for Android: [https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-android](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-android)  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native) Requires custom bindings, as MapLibre is Java-based.  | 
|  ObjectiveC  |  [https://github.com/aws-amplify/aws-sdk-ios](https://github.com/aws-amplify/aws-sdk-ios)  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native)  | 
|  ReactNative  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  |  [https://github.com/maplibre/maplibre-react-native](https://github.com/maplibre/maplibre-react-native)  | 
|  Swift  |  [https://aws.amazon.com/sdk-for-swift/](https://aws.amazon.com/sdk-for-swift/) Amazon Location Service Mobile Authentication SDK for iOS: [https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios) Amazon Location Service Mobile Tracking SDK for iOS: [https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios)  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native)  | 
|  **Partially supported**  | 
|  Flutter  |  [https://docs.amplify.aws/start/q/integration/flutter/](https://docs.amplify.aws/start/q/integration/flutter/) Flutter is not yet fully supported by AWS, but limited support is offered via Amplify.  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) The MapLibre Flutter library is considered experimental.  | 

------
#### [ Backend application ]

The following AWS SDKs are available for backend application development. MapLibre is not listed here, because map rendering is not typically needed for backend applications.


| Language | AWS SDK | 
| --- | --- | 
|  .NET  |  [https://aws.amazon.com/sdk-for-net/](https://aws.amazon.com/sdk-for-net/)  | 
|  C\$1\$1  |  [https://aws.amazon.com/sdk-for-cpp/](https://aws.amazon.com/sdk-for-cpp/)  | 
|  Go  |  [https://aws.amazon.com/sdk-for-go/](https://aws.amazon.com/sdk-for-go/)  | 
|  Java  |  [https://aws.amazon.com/sdk-for-java/](https://aws.amazon.com/sdk-for-java/)  | 
|  JavaScript  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  | 
|  Node.js  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  | 
|  TypeScript  |  [https://aws.amazon.com/sdk-for-javascript/](https://aws.amazon.com/sdk-for-javascript/)  | 
|  Kotlin  |  [https://aws.amazon.com/sdk-for-kotlin/](https://aws.amazon.com/sdk-for-kotlin/)  | 
|  PHP  |  [https://aws.amazon.com/sdk-for-php/](https://aws.amazon.com/sdk-for-php/)  | 
|  Python  |  [https://aws.amazon.com/sdk-for-python/](https://aws.amazon.com/sdk-for-python/)  | 
|  Ruby  |  [https://aws.amazon.com/sdk-for-ruby/](https://aws.amazon.com/sdk-for-ruby/)  | 
|  Rust  |  [https://aws.amazon.com/sdk-for-rust/](https://aws.amazon.com/sdk-for-rust/) The AWS SDK for Rust is in developer preview.  | 

------

# Use MapLibre tools and libraries with Amazon Location
<a name="dev-maplibre"></a>

One of the important tools for creating interactive applications with Amazon Location is MapLibre. [MapLibre](https://maplibre.org/) is primarily a rendering engine for displaying maps in a web or mobile application. However, it also includes support for plug-ins, and provides functionality for working with other aspects of Amazon Location. The following describes tools that you can use, based on the area of location that you want to work with.

**Note**  
To use any aspect of Amazon Location, install the [AWS SDK for the language that you want to use](dev-by-language.md).
+ **Maps**

  To display maps in your application, you need a map rendering engine that will use the data provided by Amazon Location, and draw to the screen. Map rendering engines also provide functionality to pan and zoom the map, or to add markers or pushpins and other annotations to the map.

  Amazon Location Service recommends rendering maps using the [MapLibre](https://github.com/maplibre/maplibre-gl-js) rendering engine. MapLibre GL JS is an engine for displaying maps in JavaScript, while MapLibre Native provides maps for either iOS or Android.

  MapLibre also has a plug-in ecosystem to extend the core functionality. For more information, visit [https://maplibre.org/maplibre-gl-js/docs/plugins/](https://maplibre.org/maplibre-gl-js/docs/plugins/).
+ **Places search**

  To make creating a search user interface simpler, you can use the [MapLibre geocoder](https://github.com/maplibre/maplibre-gl-geocoder) for web (Android applications can use the [Android Places plug-in](https://github.com/maplibre/maplibre-plugins-android/tree/master/plugin-places)).

  Use the [Amazon Location for Maplibre geocoder library](https://github.com/aws-geospatial/amazon-location-for-maplibre-gl-geocoder?tab=readme-ov-file) to simplify the process of using Amazon Location with `amazon-location-for-maplibre-gl-geocoder` in JavaScript Applications.
+ **Routes**

  To display routes on the map, use [MapLibre directions](https://github.com/maplibre/maplibre-gl-directions).
+ **Geofences and Trackers**

  MapLibre doesn't have any specific rendering or tools for geofences and tracking, but you can use the rendering functionality and [plug-ins](https://maplibre.org/maplibre-gl-js/docs/plugins/) to show the geofences and tracked devices on the map.

  The devices being tracked can use [MQTT](tracking-using-mqtt.md) or manually send updates to Amazon Location Service. Geofence events can be responded to using [AWS Lambda](https://docs.aws.amazon.com/lambda/).

Many open source libraries are available to provide additional functionality for Amazon Location Service, for example [Turf](https://github.com/Turfjs/turf) which provide spatial analysis functionality.

Many libraries use the open standard [GeoJSON](https://geojson.org/) formatted data. Amazon Location Service provides a library to support using GeoJSON in JavaScript applications. For more information, see the next section, [How to use Amazon Location SDK and libraries](dev-location-libraries.md). 

## Amazon Location MapLibre Geocoder Plugin
<a name="dev-maplibre-grocoder"></a>

The Amazon Location MapLibre geocoder plugin is designed to make it easier for you to incorporate Amazon Location functionality into your JavaScript applications, when working with map rendering and geocoding using the [maplibre-gl-geocoder](https://github.com/maplibre/maplibre-gl-geocoder) library.

Installation  
You can install Amazon Location MapLibre geocoder plugin from NPM for usage with modules, with this command:  

```
npm install @aws/amazon-location-for-maplibre-gl-geocoder
```
You can import into an HTML file for usage directly in the browser, with a script:  

```
<script src="https://www.unpkg.com/@aws/amazon-location-for-maplibre-gl-geocoder@1">/script<
```

Usage with Module  
This code sets up a Maplibre GL JavaScript map with Amazon Location geocoding capabilities. It uses authentication via Amazon Cognito Identity Pool to access Amazon Location resources. The map is rendered with a specified style and center coordinates, and allows to search for places on the map.  

```
// Import MapLibre GL JS
import maplibregl from "maplibre-gl";
// Import from the AWS JavaScript SDK V3
import { LocationClient } from "@aws-sdk/client-location";
// Import the utility functions
import { withIdentityPoolId } from "@aws/amazon-location-utilities-auth-helper";
// Import the AmazonLocationWithMaplibreGeocoder
import { buildAmazonLocationMaplibreGeocoder, AmazonLocationMaplibreGeocoder } from "@aws/amazon-location-for-maplibre-gl-geocoder"

const identityPoolId = "Identity Pool ID";
const mapName = "Map Name";
const region = "Region"; // region containing the Amazon Location resource
const placeIndex = "PlaceIndexName" // Name of your places resource in your AWS Account. 

// Create an authentication helper instance using credentials from Amazon Cognito
const authHelper = await withIdentityPoolId("Identity Pool ID");

const client = new LocationClient({
  region: "Region", // Region containing Amazon Location resources
  ...authHelper.getLocationClientConfig(), // Configures the client to use credentials obtained via Amazon Cognito
});

// Render the map
const map = new maplibregl.Map({
    container: "map",
    center: [-123.115898, 49.295868],
    zoom: 10,
    style: `https://maps.geo.${region}.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor`,
    ...authHelper.getMapAuthenticationOptions(),
});

// Gets an instance of the AmazonLocationMaplibreGeocoder Object. 
const amazonLocationMaplibreGeocoder = buildAmazonLocationMaplibreGeocoder(client, placeIndex, {enableAll: true});
    
// Now we can add the Geocoder to the map.
map.addControl(amazonLocationMaplibreGeocoder.getPlacesGeocoder());
```

Usage with a browser  
This example uses the Amazon Location Client to make a request that authenticates using Amazon Cognito.  
Some of these example use the Amazon Location Client. The Amazon Location Client is based on the [AWS SDK for JavaScript V3](https://github.com/aws/aws-sdk-js-v3) and allows for making calls to Amazon Location through a script referenced in an HTML file.
Include the following in an HTML file:  

```
< Import the Amazon Location With Maplibre Geocoder>
<script src="https://www.unpkg.com/@aws/amazon-location-with-maplibre-geocoder@1"></script>
<Import the Amazon Location Client>
<script src="https://www.unpkg.com/@aws/amazon-location-client@1"></script>
<!Import the utility library>
<script src="https://www.unpkg.com/@aws/amazon-location-utilities-auth-helper@1"></script>
```
Include the following in a JavaScript file:  

```
const identityPoolId = "Identity Pool ID";
const mapName = "Map Name";
const region = "Region"; // region containing Amazon Location resource

// Create an authentication helper instance using credentials from Amazon Cognito
const authHelper = await amazonLocationAuthHelper.withIdentityPoolId(identityPoolId);

// Render the map
const map = new maplibregl.Map({
  container: "map",
  center: [-123.115898, 49.295868],
  zoom: 10,
  style: `https://maps.geo.${region}.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor`,
  ...authHelper.getMapAuthenticationOptions(),
});

// Initialize the AmazonLocationMaplibreGeocoder object
const amazonLocationMaplibreGeocoderObject = amazonLocationMaplibreGeocoder.buildAmazonLocationMaplibreGeocoder(client, placesName, {enableAll: true});

// Use the AmazonLocationWithMaplibreGeocoder object to add a geocoder to the map. 
map.addControl(amazonLocationMaplibreGeocoderObject.getPlacesGeocoder());
```

Listed below are the functions, and commands used in the Amazon Location MapLibre geocoder plugin:
+ **`buildAmazonLocationMaplibreGeocoder`**

  This class creates an instance of the `AmazonLocationMaplibreGeocder` which is the entry point to the other all other calls:

  ```
  const amazonLocationMaplibreGeocoder = buildAmazonLocationMaplibreGeocoder(client, placesIndex, {enableAll: true});
  ```
+ **`getPlacesGeocoder`**

  Returns a ready to use IControl object that can be added directly to a map.

  ```
  const geocoder = getPlacesGeocoder();
  
  // Initialize map
  let map = await initializeMap();
  
  // Add the geocoder to the map. 
  map.addControl(geocoder);
  ```

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

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

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

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

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

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

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

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

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

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

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

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

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

**Installation**

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

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

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

**Import**

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

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

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

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

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

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

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

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

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

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

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

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

This example uses AWS SDK for JavaScript v3.

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

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

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

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

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

This example uses AWS SDK for JavaScript v3.

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

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

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

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

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

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

**Installation**

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

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

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

**Import**

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

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

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

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

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

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

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

This example uses AWS SDK for JavaScript v3.

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

...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Install the SDK in an Xcode project:

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

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

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

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

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

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

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

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

```
import AmazonLocationiOSAuthSDK
import AWSLocationXCF
```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1. Import the following classes in your code:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  `start(locationTrackingCallback: LocationTrackingCallback)`

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

  `isTrackingInForeground()`

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

  `stop()`

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

  `startTracking()`

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

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

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

  `stopBackgroundService()`

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

  `getTrackerDeviceLocation()`

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

  `getDeviceLocation(locationTrackingCallback: LocationTrackingCallback?)`

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

  `uploadLocationUpdates(locationTrackingCallback: LocationTrackingCallback?)`

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

  `enableFilter(filter: LocationFilter)`

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

  `checkFilterIsExistsAndUpdateValue(filter: LocationFilter)`

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

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

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

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

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

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

The following code sample shows the mobile tracking SDK functionality.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1. Next, import the AuthHelper in your class:

   ```
   import AmazonLocationiOSAuthSDKimport AmazonLocationiOSTrackingSDK
   ```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  `setTrackerConfig(config: LocationTrackerConfig)`

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

  `getTrackerConfig()`

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

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

  `getDeviceId()`

  Gets the location tracker's generated device Id.

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

  `startTracking()`

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

  `resumeTracking()`

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

  `stopTracking()`

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

  `startBackgroundTracking(mode: BackgroundTrackingMode)`

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

  `resumeBackgroundTracking(mode: BackgroundTrackingMode)`

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

  `stopBackgroundTracking()`

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

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

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

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

  `init()`

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

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

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

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

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

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

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

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

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

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

Start tracking the location:

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

Resume tracking the location:

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

Stop tracking the location:

```
locationTracker.stopTracking()
```

Start background tracking:

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

Resume background tracking:

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

To stop background tracking:

```
locationTracker.stopBackgroundTracking()
```

Retrieve device's tracked locations from the tracker:

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

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

# Amazon Location APIs
<a name="location-actions"></a>

Amazon Location Service provides API operations to programmatically access the location functionality. This includes APIs for Maps, Places, Routes, Trackers, Geofences, and tagging your resources. For information about the available API actions, see the [Amazon Location Service API reference](https://docs.aws.amazon.com/location-maps/latest/APIReference/Welcome.html).

You can find samples in the [Code examples](samples.md) chapter of this guide.

## Using Amazon Location with an AWS SDK
<a name="sdk-general-information-section"></a>

AWS software development kits (SDKs) are available for many popular programming languages. Each SDK provides an API, code examples, and documentation that makes it easier for developers to build AWS applications in their preferred language.

For more information about the SDKs available for use with Amazon Location Service by language, see [SDKs by language](dev-by-language.md) in this guide.

**SDK Versions**  
We recommend that you use the most recent build of the AWS SDK, and any other SDKs, that you use in your projects, and to keep the SDKs up to date. The AWS SDK provides you with the latest features and functionality, and also security updates. To find the latest build of the AWS SDK for JavaScript, for example, see the [browser installation ](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/index.html#In_the_Browser) topic in the *AWS SDK for JavaScript* documentation.

# Amazon Location API error message updates
<a name="location-actions-errorupdates"></a>

Beginning August 1, 2023, the Amazon Location team is changing API error messages as described in the following tables. Error codes will not be changed. If your applications depend on exact error message strings, you must update your applications with the new strings. For help with questions or problems, contact AWS Support.

**Topics**
+ [Places](#location-actions-errorupdates-places)
+ [Maps](#location-actions-errorupdates-maps)
+ [Trackers](#location-actions-errorupdates-trackers)
+ [Routes](#location-actions-errorupdates-routes)
+ [Metadata](#location-actions-errorupdates-metadata)
+ [Geofences](#location-actions-errorupdates-geofences)

## Places
<a name="location-actions-errorupdates-places"></a>


**Places**  

| Error code | Exception | Old error message | New error message | 
| --- | --- | --- | --- | 
|  500  |  InternalServerException  |  Internal Server Exception  |  Internal server error. Try again later.  | 
|  404  |  ResourceNotFoundException  |  resource <PlaceIndexName> not found, reason: <Reason> Resource '<PlaceIndexName>' not found placeIdx<PlaceIndexName> not found, reason: <Reason> no place index with name '%s' found  |  Place index not found: <PlaceIndexName>.  | 
|  404  |  ResourceNotFoundException  |  place not found  |  Place not found: <PlaceId>.  | 
|  400  |  ValidationException  |  PlaceIndex <PlaceIndexName> cannot be used for SearchPlaceIndexForSuggestions because it has IntendedUse <IntendedUse>  |  A place index with 'IntendedUse' set to Storage does not support 'SearchPlaceIndexForSuggestion' operation.  | 
|  400  |  ValidationException  |  only one of 'BiasPosition' or 'FilterBBox' may be set  |  Only one of 'BiasPosition' or 'FilterBBox' may be set.  | 
|  400  |  ValidationException  |  BiasPosition must have exactly 2 entries  |  'BiasPosition' must have exactly 2 entries.  | 
|  400  |  ValidationException  |  BiasPosition[0] must be between -180 and 180  |  'BiasPosition[0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  BiasPosition[1] must be between -90 and 90  |  'BiasPosition[1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  FilterBBox must have exactly 4 entries  |  'FilterBBox' must have exactly 4 entries.  | 
|  400  |  ValidationException  |  FilterBBox[0] must be between -180 and 180  |  'FilterBBox[0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  FilterBBox[1] must be between -90 and 90  |  'FilterBBox[1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  FilterBBox[2] must be between -180 and 180  |  'FilterBBox[2]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  FilterBBox[3] must be between -90 and 90  |  'FilterBBox[3]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  FilterBBox must have more southwesterly point before more northeasterly point  |  'FilterBBox' must have more southwesterly position before more northeasterly position.  | 
|  400  |  ValidationException  |  Position must have exactly 2 entries  |  'Position' must have exactly 2 entries.  | 
|  400  |  ValidationException  |  Position[0] must be between -180 and 180  |  'Position[0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  Position[1] must be between -90 and 90  |  'Position[1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  Language is not a valid BCP 47 language tag  |  'Language' must comply with the BCP 47 Language Tag standard, but was set to <GivenValue>. For more information, see https://wikipedia.org/wiki/IETF\$1language\$1tag.  | 
|  400  |  ValidationException  |  'placeID' is invalid  |  'PlaceId' must be a valid ID.  | 
|  400  |  ValidationException  |  no customer account ID parameter found  |  'RequesterAccountID' is a required field.  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  unsupported price plan '<PricingPlan>'  |  'PricingPlan' must be set to RequestBasedUsage.  | 
|  400  |  ValidationException  |  'DataSource' must be one of: Here, Esri  |  'DataSource' must be one of Esri, Grab, Here.  | 
|  400  |  ValidationException  |  Grab is only supported in the ap-southeast-1 region  |  'DataSource' Grab must only be used in following regions: ap-southeast-1.  | 
|  400  |  ValidationException  |  'IntendedUse' and 'PricingPlan' must both be provided to update either property  |  'IntendedUse' and 'PricingPlan' must both be provided to update either attribute.  | 
|  402  |  ServiceQuotaExceededException  |  Place resources per account exceeded quota limits. For more info, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/  |  Place index resources have exceeded the quota per account per region. For more information, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/.  | 
|  409  |  ConflictException  |  Resource already exists  |  Place index already exists: <PlaceIndexName>.  | 

## Maps
<a name="location-actions-errorupdates-maps"></a>


**Maps**  

| Error code | Exception | Old error message | New error message | 
| --- | --- | --- | --- | 
|  500  |  InternalServerException  |  Internal Server Exception unable to find style template Error fetching style was not able to serialize the map style file  |  Internal server error. Try again later.  | 
|  404  |  ResourceNotFoundException  |  Map not found  |  Map not found: <MapName>.  | 
|  404  |  ResourceNotFoundException  |  Sprites are not supported for this resource  |  Sprite not found: <SpriteName>.  | 
|  400  |  ValidationException  |  Resource name should be set  |  'MapName' is a required field.  | 
|  400  |  ValidationException  |  Must provide a valid number for start and end of Range  |  Font Unicode range start and end numbers must both be provided.  | 
|  400  |  ValidationException  |  Start of range is an invalid number: <StartValue>  |  Start of font Unicode range must be a valid number.  | 
|  400  |  ValidationException  |  End of range is an invalid number: <StartValue>  |  End of font Unicode range must be a valid number.  | 
|  400  |  ValidationException  |  End of range must be exactly 255 higher from start of range, difference found: <Difference>  |  The difference between the start and end of the font Unicode range must be exactly 255. Difference found: <Difference>.  | 
|  400  |  ValidationException  |  Start of range must be a multiple of 256, found <StartValue>  |  Start of font Unicode range must be a multiple of 256, but was set to: <StartValue>.  | 
|  400  |  ValidationException  |  Request font is empty  |  'FontStack' is a required field.  | 
|  400  |  ValidationException  |  Request font is not valid for the datasource <DataSource>  |  <FontStack> is not a supported font stack for data source <DataSource>. For more information about the list of supported font stacks, see https://docs.aws.amazon.com/location/previous/APIReference/API\$1GetMapGlyphs.html.  | 
|  400  |  ValidationException  |  Request font is not valid  |  <FontStack> is not a supported font stack for data source <DataSource>. For more information about the list of supported font stacks, see https://docs.aws.amazon.com/location/previous/APIReference/API\$1GetMapGlyphs.html.  | 
|  400  |  ValidationException  |  DataSource is invalid: <DataSource>  |  'DataSource' must be one of Esri, Grab, Here.  | 
|  400  |  ValidationException  |  Request filename is empty  |  'FileName' is a required field.  | 
|  400  |  ValidationException  |  Request filename is not valid  |  <SpriteFile> is not a supported sprite file name. For more information about the list of supported sprite file names, see https://docs.aws.amazon.com/location/previous/APIReference/API\$1GetMapSprites.html.  | 
|  400  |  ValidationException  |  Filename is invalid: <FileName>  |  <SpriteFile> is not a supported sprite file name. For more information about the list of supported sprite file names, see https://docs.aws.amazon.com/location/previous/APIReference/API\$1GetMapSprites.html.  | 
|  400  |  ValidationException  |  Filename is an invalid content type: <FileName>  |  <SpriteFile> is not a supported sprite file name. For more information about the list of supported sprite file names, see https://docs.aws.amazon.com/location/previous/APIReference/API\$1GetMapSprites.html.  | 
|  400  |  ValidationException  |  Filename is invalid: <FileName>  |  'Filename' must not be empty.  | 
|  400  |  ValidationException  |  y-coordinate part of 'Y' must be a valid integer  |  y- coordinate part of 'Y' must be an integer.  | 
|  400  |  ValidationException  |  tile resolution part of 'Y' must be a valid integer followed by 'x'  |  Tile resolution part of 'Y' must be an integer followed by 'X'.  | 
|  400  |  ValidationException  |  file type extension part of 'Y' must not be empty if a '.' is present  |  File type extension part of 'Y' must not be empty if a '.' is present.  | 
|  400  |  ValidationException  |  'Z' must be a valid integer  |  'Z' must be an integer.  | 
|  400  |  ValidationException  |  'X' must be a valid integer  |  'X' must be an integer.  | 
|  400  |  ValidationException  |  'Z' must not be less than minimum zoom of style '<Style>' (<MinimumValue>)  |  'Z' must not be less than minimum zoom of style <Style> (<MinimumValue>).  | 
|  400  |  ValidationException  |  'Z' must not be greater than maximum zoom of style '<Style' (<MaximumValue>)  |  'Z' must not be greater than maximum zoom of style Style (<MaximumValue>).  | 
|  400  |  ValidationException  |  'Z' value not supported  |  'Z' must be between 0 and 63.  | 
|  400  |  ValidationException  |  tile resolution part of 'Y' must be omitted because '<Style>' is a vector style  |  Tile resolution part of 'Y' must be omitted for style <Style>.  | 
|  400  |  ValidationException  |  tile resolution part of 'Y' must be at least 1  |  Tile resolution part of 'Y' must be at least 1.  | 
|  400  |  ValidationException  |  tile resolution part of 'Y' must not be greater than max resolution of style '<Style>' (<MaximumResolution>)  |  Tile resolution part of 'Y' must not be greater than maximum resolution of style <Style> (max <MaxResolution>).  | 
|  400  |  ValidationException  |  file type extension part of 'Y' must be one of <SupportedFileFormats> (or may be omitted) for style '<Style>'  |  File type extension part of 'Y' must be one of <SupportedFileFormats> (or may be omitted) for style <Style>.  | 
|  400  |  ValidationException  |  file type extension part of 'Y' must be omitted for style '<Style>'  |  File type extension part of 'Y' must be omitted for style <Style>.  | 
|  400  |  ValidationException  |  y-coordinate part of 'Y' must be an integer in the range 0..2^Zoom-1 (0..<MaxTileCoordinate>)  |  y-coordinate part of 'Y' must be an integer in the range 0..2^Zoom-1 (0..<MaxTileCoordinate>).  | 
|  400  |  ValidationException  |  'DataSource' must be one of: Here, Esri  |  'DataSource' must be one of Esri, Grab, Here.  | 
|  400  |  ValidationException  |  unsupported price plan '<PricingPlan>'  |  'PricingPlan' must be set to RequestBasedUsage.  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  Unsupported Map Style: <Style>  |  <Style> is not a supported map style. For more information about list of supported map styles, see https://docs.aws.amazon.com/location/previous/APIReference/API\$1MapConfiguration.html.  | 
|  402  |  ServiceQuotaExceededException  |  Map resources per account exceeded quota limits. For more info, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/  |  Map resources have exceeded the quota per account per region. For more information, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/.  | 
|  409  |  ConflictException  |  Resource already exists  |  Map already exists: <MapName>.  | 

## Trackers
<a name="location-actions-errorupdates-trackers"></a>


**Trackers**  

| Error code | Exception | Old error message | New error message | 
| --- | --- | --- | --- | 
|  500  |  InternalServerException  |  Internal Server Exception internal server error unable to retrieve point from the storage unable to verify tracker Error processing List request  |  Internal server error. Try again later.  | 
|  404  |  ResourceNotFoundException  |  tracker not found: <TrackerName> Tracker with name <TrackerName> was not found  |  Tracker not found: <TrackerName>.  | 
|  404  |  ResourceNotFoundException  |  association not found: TrackerName <TrackerName>; and ConsumerArn < ConsumerArn >  |  Association between tracker <TrackerName> and consumer <ConsumerArn> is not found.  | 
|  400  |  ValidationException  |  'ConsumerArn' must refer to a geofence collection resource  |  'ConsumerArn' must refer to a geofence collection resource.  | 
|  400  |  ValidationException  |  'ConsumerArn' must refer to a resource in the same region as the tracker it is associated to  |  'ConsumerArn' must refer to a resource in the same region as the tracker it is associated with.  | 
|  400  |  ValidationException  |  'ConsumerArn' must refer to a resource in the same AWS account as the tracker is it associated to  |  'ConsumerArn' must refer to a resource in the same AWS account as the tracker it is associated with.  | 
|  400  |  ValidationException  |  'DataSource' must be one of: Here, Esri  |  'DataSource' must be one of Esri, Grab, Here.  | 
|  400  |  ValidationException  |  Nothing to update.  |  At least one of the following fields must be set: 'Description', 'PositionFiltering'  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  request.TrackerName not found on request  |  'TrackerName ' is a required field.  | 
|  400  |  ValidationException  |  no deviceId parameter found  |  'DeviceId' is a required field.  | 
|  400  |  ValidationException  |  unsupported price plan '<PricingPlan>'  |  'PricingPlan' must be set to RequestBasedUsage  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  provided start time is incorrect, should follow the format YYYY-MM-DDThh:mm:ss.sssZ“  |  'StartTimeInclusive' must follow the format YYYY-MM-DDThh:mm:ss.sssZ.  | 
|  400  |  ValidationException  |  provided end time is incorrect, should follow the format YYYY-MM-DDThh:mm:ss.sssZ  |  'EndTimeExclusive' must follow the format YYYY-MM-DDThh:mm:ss.sssZ.  | 
|  400  |  ValidationException  |  end time must be after start time  |  'EndTimeExclusive' must be after 'StartTimeInclusive'.  | 
|  400  |  ValidationException  |  invalid key state  |  KMS key must be a symmetric Customer Master Key (CMK). Invalid state found. For more information about how key state affects the use of a KMS key, see https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html.  | 
|  400  |  ValidationException  |  key not found  |  Invalid KMS key. '<KmsKeyId>' <KmsKeyIdValue> not found.  | 
|  400  |  ValidationException  |  key is disabled  |  Symmetric Customer Master Key (CMK) must be enabled.  | 
|  400  |  ValidationException  |  access denied  |  Symmetric Customer Master Key (CMK) must allow Amazon Location to create grants to its KMS key.  | 
|  402  |  ServiceQuotaExceededException  |  Tracker <TrackerName> may not have more than <Max> consumer associations  |  Tracker resource may not have more than <Max> consumer associations. For more information, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/.  | 
|  402  |  ServiceQuotaExceededException  |  Trackers per account exceeded quota limits. For more info, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/  |  Tracking resources have exceeded the quota per account per region. For more information, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/.  | 
|  409  |  ConflictException  |  association already exists: TrackerName <TrackerName>; and ConsumerArn <ConsumerArn>  |  An association already exists between tracker <TrackerName> and consumer <ConsumerArn>.  | 
|  409  |  ConflictException  |  Tracker already exists: <TrackerName>  |  Tracker already exists: <TrackerName>.  | 

## Routes
<a name="location-actions-errorupdates-routes"></a>


**Routes**  

| Error code | Exception | Old error message | New error message | 
| --- | --- | --- | --- | 
|  500  |  InternalServerException  |  Internal Server Exception  |  Internal server error. Try again later.  | 
|  404  |  ResourceNotFoundException  |  Resource not found  |  Route calculator not found: <RouteCalculatorName>.  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  'DataSource' must be one of: Here, Esri, Grab  |  'DataSource' must be one of Esri, Grab, Here.  | 
|  400  |  ValidationException  |  <PricingPlan> pricing plan is not supported  |  'PricingPlan' must be set to RequestBasedUsage  | 
|  400  |  ValidationException  |  unsupported price plan '<PricingPlan>'  |  'PricingPlan' must be set to RequestBasedUsage  | 
|  400  |  ValidationException  |  Grab is only supported in the ap-southeast-1 region  |  'DataSource' <DataSourceName> must only be used in following regions: ap-southeast-1.  | 
|  400  |  ValidationException  |  PricingPlan must be 'RequestBasedUsage'  |  'PricingPlan' must be set to RequestBasedUsage.  | 
|  400  |  ValidationException  |  'DeparturePositions[0][0]' must be between -180 and 180  |  'DeparturePositions[0][0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  'DeparturePositions[0][1]' must be between -90 and 90  |  'DeparturePositions[0][1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  'DestinationPositions[0][0]' must be between -180 and 180  |  'DestinationPositions[0][0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  'DestinationPositions[0][1]' must be between -90 and 90.  |  'DestinationPositions[0][1]' must be between -90 and 90  | 
|  400  |  ValidationException  |  'DepartNow' may not be true if 'DepartureTime' is set  |  Only one of 'DepartNow' or 'DepartureTime' may be set.  | 
|  400  |  ValidationException  |  '<TravelModeOption>'' may not be set when 'TravelMode' has value <TravelModeOption>  |  '<TravelModeOption>' must not be set when 'TravelMode' has value <TravelModeOption>.  | 
|  400  |  ValidationException  |  'CarModeOptions' may not be set when 'TravelMode' has value Walking  |  'CarModeOptions' must not be set when 'TravelMode' has value Walking.  | 
|  400  |  ValidationException  |  'TruckModeOptions' may not be set when 'TravelMode' has value Walking  |  'TruckModeOptions' must not be set when 'TravelMode' has value Walking.  | 
|  400  |  ValidationException  |  'TruckModeOptions' may not be set when 'TravelMode' has value Car  |  'TruckModeOptions' must not be set when 'TravelMode' has value Car.  | 
|  400  |  ValidationException  |  'CarModeOptions' may not be set when 'TravelMode' has value Truck  |  'CarModeOptions' must not be set when 'TravelMode' has value Truck.  | 
|  400  |  ValidationException  |  At least one of [Height, Length, Width] must be set in 'TruckModeOptions.Dimensions'  |  At least one of the following attribute must be set in TruckModeOptions.Dimensions: Height, Length, Width.  | 
|  400  |  ValidationException  |  At least one of [Total] must be set in 'TruckModeOptions.Weight'  |  At least one of the following attribute must be set in TruckModeOptions.Weight: Total.  | 
|  400  |  ValidationException  |  'DeparturePositions' count must be 10 or less with DataSource set to Esri  |  'DeparturePositions' must have length at most 10 for 'DataSource' Esri.  | 
|  400  |  ValidationException  |  'DestinationPositions' count must be 10 or less with DataSource set to Esri  |  'DestinationPositions' must have length at most 10 for 'DataSource' Esri.  | 
|  400  |  ValidationException  |  'DeparturePositions[0]' is more than 40km away from 'DestinationPositions[0]'  |  'DeparturePositions[0]' must not be more than 40 km away from 'DestinationPositions[0]'.  | 
|  400  |  ValidationException  |  'DeparturePositions[0]' is more than 400km away from 'DestinationPositions[0]'  |  'DeparturePositions[0]' must not be more than 400 km away from 'DestinationPositions[0]'.  | 
|  400  |  ValidationException  |  DeparturePositions[0] is contained within an unsupported region. Korea is not supported for CalculateRouteMatrix with the provider Esri.  |  DeparturePositions[0] is located in Korea, which is not supported when using CalculateRouteMatrix with data provider Esri.  | 
|  400  |  ValidationException  |  '<HereTruckDimension>' must be between <Min> and <Max> <Unit>  |  'HereTruckDimension' must be between <Min> and <Max> <Unit>.  | 
|  400  |  ValidationException  |  'WaypointPositions[0][0]' must be between -180 and 180  |  'WaypointPositions[0][0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  'WaypointPositions[0][1]' must be between -90 and 90  |  'WaypointPositions[0][1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  'WaypointPositions[1][0]' must be between -180 and 180  |  'WaypointPositions[1][0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  'WaypointPositions[1][1]' must be between -90 and 90  |  'WaypointPositions[1][1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  No road segment could be matched for one or more coordinates within a radius (1km)  |  One or more provided positions are more than 1 km from the nearest road segment.  | 
|  400  |  ValidationException  |  Some positions in the request are unreachable  |  Some positions in the request are unreachable.  | 
|  400  |  ValidationException  |  Total distance between all waypoints must be not be greater than 40km for DataSource Esri when using TravelMode Walking  |  Total distance between all route positions must not be greater than 40 km for 'DataSource' Esri and 'TravelMode' Walking.  | 
|  400  |  ValidationException  |  Total distance between all waypoints must be not be greater than 400km for DataSource Esri  |  Total distance between all route positions must not be greater than 400 km for 'DataSource' Esri.  | 
|  400  |  ValidationException  |  Following positions in the request are unreachable: <UnreachablePositions>  |  The following positions are unreachable: <UnreachablePositions>.  | 
|  400  |  ValidationException  |  'DepartureTime' contains a badly-formatted timestamp  |  'DepartureTime' must follow the format YYYY-MM-DDThh:mm:ss.sssZ.  | 
|  400  |  ValidationException  |  'TravelMode' <TravelMode> is not supported by <DataProvider>  |  'TravelMode' <TravelMode> not supported by data provider <DataProvider>.  | 
|  400  |  ValidationException  |  'DeparturePositions' must be set  |  'DeparturePositions' must not be empty.  | 
|  400  |  ValidationException  |  'DestinationPositions' must be set  |  'DestinationPositions' must not be empty.  | 
|  400  |  ValidationException  |  Some inputs in the request are invalid  |  Some inputs in the request are invalid.  | 
|  400  |  ValidationException  |  No route found between position <FirstPosition> and position <SecondPosition>  |  No route found between position <FirstPosition> and position <SecondPosition>.  | 
|  400  |  ValidationException  |  No route found  |  No route found. For more information, see https://developer.here.com/documentation/routing-api/dev\$1guide/topics/notice.html.  | 
|  400  |  ValidationException  |  No route found  |  No route found.  | 
|  402  |  ServiceQuotaExceededException  |  Route calculators per account exceeded quota limits. For more info, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/  |  Route calculator resources have exceeded the quota per account per region. For more information, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/.  | 
|  409  |  ConflictException  |  Resource already exists  |  Route calculator already exists: <RouteCalculatorName>.  | 

## Metadata
<a name="location-actions-errorupdates-metadata"></a>


**Metadata**  

| Error code | Exception | Old error message | New error message | 
| --- | --- | --- | --- | 
|  500  |  InternalServerException  |  Internal Server Error Error processing List request  |  Internal server error. Try again later.  | 
|  404  |  ResourceNotFoundException  |  APIKey not found  |  Api key not found: <APIKeyName>.  | 
|  404  |  ResourceNotFoundException  |  APIKeyID not found  |  ApiKeyId not found: <APIKeyID>.  | 
|  400  |  ValidationException  |  Either ExpireTime or NoExpiry must be provided  |  At least one of the following fields must be set: 'ExpireTime', 'NoExpiry'.  | 
|  400  |  ValidationException  |  NoExpiry cannot be set to false if no ExpireTime is provided  |  'ExpireTime' must be set when 'NoExpiry' has value false.  | 
|  400  |  ValidationException  |  ExpireTime cannot be set if NoExpiry is true  |  'ExpireTime' must not be set when 'NoExpiry' has value true.  | 
|  400  |  ValidationException  |  Expire time '<ExpireTimeValue>' is not a valid time format  |  'ExpireTime' must follow the format YYYY-MM-DDThh:mm:ss.sssZ.  | 
|  400  |  ValidationException  |  Expire time '<ExpireTimeValue>' cannot be in the past when creating a key  |  'ExpireTime' must not be in the past.  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  The API Key %s has been recently used and the requested update may impact current usage. Specify ForceUpdate=true to update the API Key configuration.  |  This update may cause some users to lose API access. Because this API Key has been used in the last 7 days, you must set 'ForceUpdate' to true to confirm this change.  | 
|  400  |  ValidationException  |  Expire time '<ExpireTimeValue>' must not be more than 1 minute in the past  |  'ExpireTime' must not be more than 1 minute in the past.  | 
|  400  |  ValidationException  |  Description, ExpireTime, NoExpiry and Restrictions can't all be empty  |  At least one of the following fields must be set: 'Description', 'ExpireTime', 'NoExpiry', 'Restrictions'.  | 
|  400  |  ValidationException  |  API Key expired  |  'ApiKeyId' must not be expired.  | 
|  409  |  ConflictException  |  API key named <APIKeyName> already exists  |  Api key already exists: <APIKeyName>.  | 

## Geofences
<a name="location-actions-errorupdates-geofences"></a>


**Geofences**  

| Error code | Exception | Old error message | New error message | 
| --- | --- | --- | --- | 
|  500  |  InternalServerException  |  internal server error Internal server error Unsupported geofence geometry encountered geometry marshal error geometry load error unable to get geofence collection unable to delete geofences unable to retrieve geofence Error processing List request  |  Internal server error. Try again later.  | 
|  404  |  ResourceNotFoundException  |  collection not found: <GeofenceCollectionName> <GeofenceCollectionName> geofence collection not found Resource not found error no geofence with given name found  |  Geofence Collection not found: <GeofenceCollectionName>.  | 
|  400  |  ValidationException  |  unsupported price plan '<PricingPlan>'  |  'PricingPlan' must be set to RequestBasedUsage.  | 
|  400  |  ValidationException  |  KMS key must be a symmetric CMK. Invalid usage type: <UsageType>  |  KMS key must be a symmetric Customer Master Key (CMK). Invalid usage type <UsageType>. For how to create a symmetric CMK, refer to https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html\$1create-symmetric-cmk.  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  PricingPlanDataSource cannot be updated without updating PricingPlan  |  'PricingPlan' must be provided to update 'PricingPlanDataSource'.  | 
|  400  |  ValidationException  |  nothing to update  |  At least one of the following fields must be set: 'Description'  | 
|  400  |  ValidationException  |  invalid key state  |  KMS key must be a symmetric Customer Master Key (CMK). Invalid state <InvalidState>. For more information about how key state affects the use of a KMS key, see https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html.  | 
|  400  |  ValidationException  |  key not found  |  Invalid KMS key. '<KmsKeyId>' <KmsKeyIdValue> not found.  | 
|  400  |  ValidationException  |  key is disabled  |  Symmetric Customer Master Key (CMK) must be enabled.  | 
|  400  |  ValidationException  |  access denied  |  Symmetric Customer Master Key (CMK) must allow Amazon Location to create grants to its KMS key.  | 
|  400  |  ValidationException  |  duplicate geofence ID in batch  |  'GeofenceId' <DuplicatedGeofenceID> is duplicated in batch.  | 
|  400  |  ValidationException  |  missing GeofenceId  |  'GeofenceId' must not be empty.  | 
|  400  |  ValidationException  |  Invalid token  |  'NextToken' must be a valid token.  | 
|  400  |  ValidationException  |  Expired token  |  'NextToken' must not be expired.  | 
|  400  |  ValidationException  |  Position[0] must be between -180 and 180  |  'Position[0]' must be between -180 and 180.  | 
|  400  |  ValidationException  |  Position[1] must be between -90 and 90  |  'Position[1]' must be between -90 and 90.  | 
|  400  |  ValidationException  |  radius must be less than or equal to 1000km  |  'Geometry.Circle.Radius' must be less than or equal to 1000km.  | 
|  400  |  ValidationException  |  no geofence with given name found  |  Geofence not found: <CollectionName>.  | 
|  400  |  ValidationException  |  Geometry must contain either a Circle or Polygon, not both  |  Only one of 'Circle' or 'Polygon' may be set within 'Geometry'.  | 
|  400  |  ValidationException  |  Geometry must contain a Polygon or a Circle  |  One of 'Polygon' or 'Circle' must be set within 'Geometry'.  | 
|  400  |  ValidationException  |  radius must be greater than 0m  |  'Geometry.Circle.Radius' must be greater than 0m.  | 
|  400  |  ValidationException  |  empty polygon  |  'Geometry.Polygon' must not be empty.  | 
|  400  |  ValidationException  |  empty polygon ring  |  'Geometry.Polygon' must not be empty.  | 
|  400  |  ValidationException  |  circle can not cross antimeridian  |  'Geometry.Circle' must not cross antimeridian. Cut it in two such that neither part's representation crosses the antimeridian.  | 
|  400  |  ValidationException  |  polygon can not cross antimeridian  |  'Geometry.Polygon' must not cross antimeridian. Cut it in two such that neither part's representation crosses the antimeridian.  | 
|  400  |  ValidationException  |  polygon can not have interior rings (holes), remove holes  |  'Geometry.Polygon' must not have interior rings (holes). For more information about interior rings see https://www.rfc-editor.org/rfc/rfc7946.html\$1appendix-A.3.  | 
|  400  |  ValidationException  |  polygon ring is not closed  |  'Geometry.Polygon' contains an open ring. Close the ring by ensuring the first and last positions are equal.  | 
|  400  |  ValidationException  |  polygon ring has more than 1000 vertices  |  'Geometry.Polygon' must not have more than 1000 vertices.  | 
|  400  |  ValidationException  |  polygon ring has fewer than 4 positions  |  Number of vertices in 'Geometry.Polygon' must be greater or equal to 4.  | 
|  400  |  ValidationException  |  invalid center  |  'Geometry.Circle.Center' must be a valid position (longitude/latitude pair).  | 
|  400  |  ValidationException  |  radius must be greater than 0m  |  'Geometry.Circle.Radius' must be greater than 0 m.  | 
|  400  |  ValidationException  |  longitude range should be between -180 and 180 degrees  |  Longitude must be between -180 and 180 degrees, but was set to <ProvidedLongitude>.  | 
|  400  |  ValidationException  |  latitude range should be between -90 and 90 degrees  |  Latitude must be between -90 and 90 degrees, but was set to <ProvidedLongitude>.  | 
|  400  |  ValidationException  |  polygon exterior ring is expected to be counter clockwise  |  'Geometry.Polygon' must be oriented counter-clockwise.  | 
|  400  |  ValidationException  |  polygon interior ring should be clockwise oriented  |  'Geometry.Polygon' must be oriented clockwise.  | 
|  400  |  ValidationException  |  radius must be less than or equal to 1000km  |  'Geometry.Circle.Radius' must be less than or equal to 1000 km.  | 
|  400  |  ValidationException  |  timestamp.Parse() error  |  'SampleTime' must follow the format YYYY-MM-DDThh:mm:ss.sssZ.  | 
|  400  |  ValidationException  |  invalid input  |  'SourceArn' must refer to a tracker resource.  | 
|  400  |  ValidationException  |  arn: invalid prefix  |  'SourceArn' must be a valid ARN. For more information, see https://docs.aws.amazon.com/general/latest/gr/AWS-arns-and-namespaces.html.  | 
|  400  |  ValidationException  |  arn: not enough sections  |  'SourceArn' must be a valid ARN. For more information, see https://docs.aws.amazon.com/general/latest/gr/AWS-arns-and-namespaces.html.  | 
|  400  |  ValidationException  |  invalid resource part  |  'SourceArn' must refer to a tracker resource.  | 
|  402  |  ServiceQuotaExceededException  |  Geofence collections per account exceeded quota limits. For more info, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/  |  Geofence collection resources have exceeded the quota per account per region. For more information, see https://aws.amazon.com/premiumsupport/knowledge-center/manage-service-limits/.  | 
|  409  |  ConflictException  |  collection already exists: <GeofenceCollectionName>  |  Geofence Collection already exists: <GeofenceCollectionName>.  | 
|  409  |  ConflictException  |  Resource conflict error  |  Geofence already exists: <GeofenceName>.  | 

# Code examples and tutorials for working with Amazon Location Service
<a name="samples"></a>

This topic shows a list of code examples, tutorials, and blog posts to help you learn about Amazon Location Service. Each code example includes a description of how it works.

You can find additional samples on the [AWS Geospatial GitHub page](https://github.com/orgs/aws-geospatial/repositories), the [AWS samples GitHub page for Amazon Location](https://github.com/aws-samples/amazon-location-samples), and on the [AWS blog site](https://aws.amazon.com/blogs/mobile/category/mobile-services/amazon-location/).

**Note**  
It is good to understand the difference between the AWS Geospatial GitHub page and the AWS samples GitHub page.  
**Geospatial GitHub** – The [AWS Geospatial GitHub page](https://github.com/orgs/aws-geospatial/repositories) includes samples that are created and maintained by the Amazon Location Service team.
**Samples GitHub** – The [AWS samples GitHub page for Amazon Location](https://github.com/aws-samples/amazon-location-samples) includes samples that were created for Amazon Location, but may or may not be actively maintained.

The [quick start](sample-quick-start.md) tutorial is a good place to start before using other samples, as it shows how to complete prerequisites that are useful for most of the samples.

**Example availability**  
Can't find what you need? Request a new code example by using the **Provide feedback** link at the bottom of this page.

**Topics**
+ [Amazon Location Demo site](sample-demo-site.md)
+ [Tutorial: Quick start](sample-quick-start.md)
+ [Tutorial: Database enrichment](example-validate-database.md)
+ [Example: Explore app](example-explore.md)
+ [Example: Style a map](example-switch-styles.md)
+ [Example: Draw markers](example-draw-markers.md)
+ [Example: Draw clustered points](example-draw-clusters.md)
+ [Example: Draw a polygon](example-draw-polygon.md)
+ [Example: Change the map language](example-map-language.md)
+ [Blog: Estimated delivery time notifications](example-delivery-notifications.md)
+ [Example: Stream Position Updates](example-stream-position-updates.md)
+ [Example: Geofencing and Tracking mobile application](example-tracking-geofencing.md)

# Amazon Location Demo site
<a name="sample-demo-site"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/location-demo-site-samples.png)


You can see demos with source code of Amazon Location Service in action at the [Amazon Location Demo site](https://location.aws.com/). This site includes a [hosted web demo](https://location.aws.com/demo), and also a demo app for [Android](https://play.google.com/store/apps/details?id=com.aws.amazonlocation).

You can also find a wide array of samples, filterable by features, language, and platform in the site's [Samples](https://location.aws.com/samples) page.

# Tutorial: Quick start
<a name="sample-quick-start"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/quickstart-both.png)


There are quick start tutorials available for web, iOS, and Android devices. For each platform, the tutorial shows you how to add an interactive map to an application, and how to make calls to the Amazon Location Service APIs from your application. The tutorial is available for JavaScript in a static webpage, Kotlin for an Android phone application, or Swift for an iOS application.
+ JavaScript for a static webpage documentation link: [Create a web app to use Amazon Location Service](qs-web.md)
+ Kotlin for an Android application documentation link: [Quick start with Amazon Location Service](getting-started.md)
+ Swift for an iOS app documentation link: [Create an iOS app for Amazon Location Service](qs-ios.md)

# Tutorial: Database enrichment
<a name="example-validate-database"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/database-validation_small.png)


This tutorial shows you how to use Amazon Location Service, called from AWS Lambda to normalize addresses and add latitude and longitude to records in an Amazon Aurora database. Uses Amazon Aurora and AWS Lambda.

Documentation link: [Amazon Aurora PostgreSQL user-defined functions for Amazon Location Service](database-address-validation.md)

# Example: Explore app
<a name="example-explore"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/ExploreSample_small.png)


One of the best ways to learn about the functionality of Amazon Location Service is to use the [Explore functionality](https://console.aws.amazon.com/location/explore/home) within the Amazon Location console. This full web application example mimics the maps, places, routes, geofences, and trackers functionality from the console to show you how to recreate these features in your own app. Uses Amplify, React, and JavaScript.

Samples GitHub link: [Explore sample application](https://github.com/aws-samples/amazon-location-samples/tree/main/amplify-ui-geo-explore)

# Example: Style a map
<a name="example-switch-styles"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/map-styles-both_small.png)


This code example shows how to switch between a satellite map and a vector road map, using MapLibre in JavaScript. Uses MapLibre, the Amazon Location authentication helper, and JavaScript.

Geospatial GitHub link: [Interactive map with style switching](https://github.com/aws-geospatial/amazon-location-samples-js/tree/main/map-style-change)

# Example: Draw markers
<a name="example-draw-markers"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/markers_small.png)


This code example shows Amazon Locker locations in Vancouver, BC, Canada. It shows how to draw markers at point locations. Uses MapLibre, Node.js, React, the Amazon Location authentication helper and JavaScript.

Geospatial GitHub link: [Interactive map with markers at points](https://github.com/aws-geospatial/amazon-location-samples-react/tree/main/map-with-markers)

# Example: Draw clustered points
<a name="example-draw-clusters"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/clusters_small.png)


Using USGS earthquake data, this code example shows how to draw points that cluster together when they are close together on the map. Uses MapLibre, Node.js, React, Amplify, and JavaScript.

Samples GitHub link: [Interactive map with clusters of points](https://github.com/aws-samples/amazon-location-samples/tree/main/react-map-gl-clusters)

# Example: Draw a polygon
<a name="example-draw-polygon"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/polygons_small.png)


This code example shows how to draw a polygon on the map. Uses MapLibre, Node.js, React, the Amazon Location authentication helper, and JavaScript.

Geospatial GitHub link: [Interactive map with polygons](https://github.com/aws-geospatial/amazon-location-samples-react/tree/main/map-with-geojson)

# Example: Change the map language
<a name="example-map-language"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/language-japanese_small.png)


This code example shows how you can change the display language of maps in Amazon Location. Uses Amplify, React, and MapLibre.

Samples GitHub link: [Change Map Language Sample](https://github.com/aws-samples/amazon-location-samples/tree/main/react-map-gl-change-map-language?)

# Blog: Estimated delivery time notifications
<a name="example-delivery-notifications"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/proximity-notifications_small.png)


This blog post shows different ways to notify customers with estimated delivery times. It explains using routes to show estimated driving time, and then using trackers and geofences to notify when a driver gets close to the customer. Uses Amplify, React, Amazon EventBridge, and Amazon Simple Notification Service (Amazon SNS).

Blog link: [Estimated Time of Arrival and Proximity Notifications](https://aws.amazon.com/blogs/mobile/implementing-estimated-time-of-arrival-and-proximity-notifications-for-delivery-using-amazon-location-service/)

# Example: Stream Position Updates
<a name="example-stream-position-updates"></a>

![\[alt text not found\]](http://docs.aws.amazon.com/location/previous/developerguide/images/samples/sampleappgeofenceKVS1.png)


**Kinesis Stream To Tracker App**: This sample demonstrates how to use Kinesis Data Stream to post tracker updates with Amazon Location Service. The sample is a deployable lambda application written in python that can be integrated with a Kinesis Data Stream to consume the Kinesis events and batch update device positions.

Repository link: [ Amazon Location Amazon Kinesis Data Streams Stream To Tracker App](https://github.com/aws-geospatial/amazon-location-stream-device-data-to-tracker-lambda)

For more information on tracking and geofences, see the [Geofences and Trackers](https://docs.aws.amazon.com/location/previous/developerguide/geofence-tracker-concepts.html) documentation. Developers can deploy the app by following the [AWS's Serverless Application Repository](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverlessrepo-how-to-consume.html) documentation, or dicretly from the [Lambda console](https://console.aws.amazon.com/lambda/home#/create/app?applicationId=arn:aws:serverlessrepo:us-east-1:003883091127:applications/kinesis-stream-device-data-to-amazon-location-tracker).

**Device Position Streaming Sample App**: This code example shows how to stream device position data to a Kinesis Data Stream and how geofence notifications work. This app depends on the Kinesis Stream to Tracker Sample App, listed above, to be running for the streamed tracker positions to be updated in Amazon Location Service.

Repository link: [Amazon Location Device Position Streaming Sample App](https://github.com/aws-geospatial/amazon-location-samples-react/tree/main/tracking-data-streaming)

# Example: Geofencing and Tracking mobile application
<a name="example-tracking-geofencing"></a>

This sample application shows how a tracker and geofence interact using a combination of Lambda, AWS IoT and Amazon Location features. There are tutorials avaible for iOS and Android.

Tutorial link: [Sample Geofence and Tracker mobile application](https://docs.aws.amazon.com//location/previous/developerguide/geofence-tracking-tutorials.html)