

# SDKs and frameworks for 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, Routes, Geofencing, 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 [Use MapLibre tools and related libraries with Amazon Location](dev-maplibre.md).
+ **Amazon Location SDKs** – The Amazon Location SDKs are 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 SDKs, see [SDKs by language](dev-by-language.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.

# Developer tutorials
<a name="sdk-how-to"></a>

Use this section to learn how to use various aspects of the Amazon Location Service SDK.

**Topics**
+ [

# How to use authentication helpers
](how-to-auth-helper.md)
+ [

# Use Amazon Location MapLibre Geocoder GL plugin
](dev-maplibre-geocoder.md)
+ [

# How to use Tracking SDKs
](dev-tracking-sdk.md)
+ [

# Use MapLibre tools and related libraries with Amazon Location
](dev-maplibre.md)

# How to use authentication helpers
<a name="how-to-auth-helper"></a>

This section provides additional information about authentication helpers.

## Web
<a name="loc-sdk-auth-web"></a>

The Amazon Location JavaScript authentication utilities assist in authenticating when making Amazon Location Service API calls from JavaScript applications. These utilities specifically support authentication using API keys or Amazon Cognito.

**Installation**
+ Install this library using NPM:

  ```
  npm install @aws/amazon-location-utilities-auth-helper
  ```
+ To use it directly in the browser, include the following in your HTML file:

  ```
  <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>
  ```

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

To use the authentication helpers, import the library and call the necessary utility functions. This library supports authenticating requests from the Amazon Location Service SDKs, including the [Maps](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-maps/), [Places](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-places/), and [Routes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-routes/) standalone SDKs, as well as rendering maps with [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js).

**Usage with Modules**

This example demonstrates the use of the standalone Places SDK to make a request authenticated with API keys:

```
npm install @aws-sdk/client-geo-places

import { GeoPlacesClient, GeocodeCommand } from "@aws-sdk/client-geo-places";
import { withAPIKey } from "@aws/amazon-location-utilities-auth-helper";

const authHelper = withAPIKey("<API Key>", "<Region>");
const client = new GeoPlacesClient(authHelper.getClientConfig());

const input = { ... };
const command = new GeocodeCommand(input);
const response = await client.send(command);
```

This example demonstrates the use of the standalone Routes SDK to make a request authenticated with API keys:

```
npm install @aws-sdk/geo-routes-client

import { GeoRoutesClient, CalculateRoutesCommand } from "@aws-sdk/geo-routes-client";
import { withAPIKey } from "@aws/amazon-location-utilities-auth-helper";

const authHelper = withAPIKey("<API Key>", "<Region>");
const client = new GeoRoutesClient(authHelper.getClientConfig());

const input = { ... };
const command = new CalculateRoutesCommand(input);
const response = await client.send(command);
```

This example uses the Location SDK with API key authentication:

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

import { LocationClient, ListGeofencesCommand } from "@aws-sdk/client-location";
import { withAPIKey } from "@aws/amazon-location-utilities-auth-helper";

const authHelper = withAPIKey("<API Key>", "<Region>");
const client = new LocationClient(authHelper.getClientConfig());

const input = { ... };
const command = new ListGeofencesCommand(input);
const response = await client.send(command);
```

**Usage with Browser**

Utility functions are accessible under the amazonLocationAuthHelper global object when used directly in a browser environment.

This example demonstrates a request with the Amazon Location Client, authenticated using API keys:

```
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1"></script>

const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
const client = new amazonLocationClient.GeoRoutesClient(authHelper.getClientConfig());
const input = { ... };
const command = new amazonLocationClient.routes.CalculateRoutesCommand(input);
const response = await client.send(command);
```

This example demonstrates rendering a map with MapLibre GL JS, authenticated with an API key:

```
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x"></script>

const apiKey = "<API Key>";
const region = "<Region>";
const styleName = "Standard";

const map = new maplibregl.Map({
  container: "map",
  center: [-123.115898, 49.295868],
  zoom: 10,
  style: `https://maps.geo.${region}.amazonaws.com/v2/styles/${styleName}/descriptor?key=${apiKey}`,
});
```

This example demonstrates rendering a map with MapLibre GL JS using Amazon Cognito:

```
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x"></script>
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>

const identityPoolId = "<Identity Pool ID>";
const authHelper = await amazonLocationAuthHelper.withIdentityPoolId(identityPoolId);

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

**Alternative Usage with Authenticated Identities**

You can modify the withIdentityPoolId function to include custom parameters for authenticated identities:

```
const userPoolId = "<User Pool ID>";

const authHelper = await amazonLocationAuthHelper.withIdentityPoolId(identityPoolId, {
  logins: {
    [`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: "cognito-id-token"
  }
});
```

## iOS
<a name="loc-sdk-auth-ios"></a>

The Amazon Location Service Mobile Authentication SDK for iOS helps authenticate requests to Amazon Location Service APIs from iOS applications. It specifically supports authentication via API keys or Amazon Cognito.

**Installation**
+ Open Xcode and go to **File > Add Package Dependencies**.
+ 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 Enter.
+ Select the "amazon-location-mobile-auth-sdk-ios" package and click **Add Package**.
+ Choose the "AmazonLocationiOSAuthSDK" package product and click **Add Package**.

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

After installing the library, use the `AuthHelper` class to configure client settings for either API keys or Amazon Cognito.

**API Keys**

Here is an example using the standalone Places SDK with API key authentication:

```
import AmazonLocationiOSAuthSDK
import AWSGeoPlaces

func geoPlacesExample() {
    let apiKey = "<API key>"
    let region = "<Region>"

    let authHelper = try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    let client: GeoPlacesClient = GeoPlacesClient(config: authHelper.getGeoPlacesClientConfig())

    let input = AWSGeoPlaces.SearchTextInput(
        biasPosition: [-97.7457518, 30.268193],
        queryText: "tacos"
    )

    let output = try await client.searchText(input: input)
}
```

Here is an example using the standalone Routes SDK with API key authentication:

```
import AmazonLocationiOSAuthSDK
import AWSGeoRoutes

func geoRoutesExample() {
    let apiKey = "<API key>"
    let region = "<Region>"

    let authHelper = try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    let client: GeoRoutesClient = GeoRoutesClient(config: authHelper.getGeoRoutesClientConfig())

    let input = AWSGeoRoutes.CalculateRoutesInput(
        destination: [-123.1651031, 49.2577281],
        origin: [-97.7457518, 30.268193]
    )

    let output = try await client.calculateRoutes(input: input)
}
```

Here is an example using the Location SDK with API key authentication:

```
import AmazonLocationiOSAuthSDK
import AWSLocation

func locationExample() {
    let apiKey = "<API key>"
    let region = "<Region>"

    let authHelper = try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    let client: LocationClient = LocationClient(config: authHelper.getLocationClientConfig())

    let input = AWSLocation.ListGeofencesInput(
        collectionName: "<Collection name>"
    )

    let output = try await client.listGeofences(input: input)
}
```

Here is an example using the standalone Places SDK with Amazon Cognito:

```
import AmazonLocationiOSAuthSDK
import AWSGeoPlaces

func geoPlacesExample() {
    let identityPoolId = "<Identity Pool ID>"

    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)
    let client: GeoPlacesClient = GeoPlacesClient(config: authHelper.getGeoPlacesClientConfig())

    let input = AWSGeoPlaces.SearchTextInput(
        biasPosition: [-97.7457518, 30.268193],
        queryText: "tacos"
    )

    let output = try await client.searchText(input: input)
}
```

Here is an example using the standalone Routes SDK with Amazon Cognito:

```
import AmazonLocationiOSAuthSDK
import AWSGeoRoutes

func geoRoutesExample() {
    let identityPoolId = "<Identity Pool ID>"

    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)
    let client: GeoRoutesClient = GeoRoutesClient(config: authHelper.getGeoRoutesClientConfig())

    let input = AWSGeoRoutes.CalculateRoutesInput(
        destination: [-123.1651031, 49.2577281],
        origin: [-97.7457518, 30.268193]
    )

    let output = try await client.calculateRoutes(input: input)
}
```

Here is an example using the Location SDK with Amazon Cognito:

```
import AmazonLocationiOSAuthSDK
import AWSLocation

func locationExample() {
    let identityPoolId = "<Identity Pool ID>"

    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)
    let client: LocationClient = LocationClient(config: authHelper.getLocationClientConfig())

    let input = AWSLocation.ListGeofencesInput(
        collectionName: "<Collection name>"
    )

    let output = try await client.listGeofences(input: input)
}
```

## Android
<a name="loc-sdk-auth-android"></a>

The Amazon Location Service Mobile Authentication SDK for Android helps you authenticate requests to Amazon Location Service APIs from Android applications, specifically supporting authentication using Amazon Cognito.

**Installation**
+ This authentication SDK works with the overall AWS Kotlin SDK. Both SDKs are published to Maven Central. Check the latest version of the [auth SDK](https://mvnrepository.com/artifact/software.amazon.location/auth) on Maven Central.
+ Add the following lines to the dependencies section of your `build.gradle` file in Android Studio:

  ```
  implementation("software.amazon.location:auth:1.1.0")
  implementation("org.maplibre.gl:android-sdk:11.5.2")
  implementation("com.squareup.okhttp3:okhttp:4.12.0")
  ```
+ For the standalone Maps, Places, and Routes SDKs, add the following lines:

  ```
  implementation("aws.sdk.kotlin:geomaps:1.3.65")
  implementation("aws.sdk.kotlin:geoplaces:1.3.65")
  implementation("aws.sdk.kotlin:georoutes:1.3.65")
  ```
+ For the consolidated Location SDK that includes Geofencing and Tracking, add the following line:

  ```
  implementation("aws.sdk.kotlin:location:1.3.65")
  ```

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

Import the following classes in your code:

```
// For the standalone Maps, Places, and Routes SDKs
import aws.sdk.kotlin.services.geomaps.GeoMapsClient
import aws.sdk.kotlin.services.geoplaces.GeoPlacesClient
import aws.sdk.kotlin.services.georoutes.GeoRoutesClient

// For the consolidated Location SDK
import aws.sdk.kotlin.services.location.LocationClient

import software.amazon.location.auth.AuthHelper
import software.amazon.location.auth.LocationCredentialsProvider
import software.amazon.location.auth.AwsSignerInterceptor
import org.maplibre.android.module.http.HttpRequestUtil
import okhttp3.OkHttpClient
```

You can create an `AuthHelper` and use it with the AWS Kotlin SDK:

**Example: Credential Provider with Identity Pool ID**

```
private suspend fun exampleCognitoLogin() {
    val authHelper = AuthHelper.withCognitoIdentityPool("MY-COGNITO-IDENTITY-POOL-ID", applicationContext)
    
    var geoMapsClient = GeoMapsClient(authHelper?.getGeoMapsClientConfig())
    var geoPlacesClient = GeoPlacesClient(authHelper?.getGeoPlacesClientConfig())
    var geoRoutesClient = GeoRoutesClient(authHelper?.getGeoRoutesClientConfig())
    
    var locationClient = LocationClient(authHelper?.getLocationClientConfig())
}
```

**Example: Credential Provider with Custom Credential Provider**

```
private suspend fun exampleCustomCredentialLogin() {
    var authHelper = AuthHelper.withCredentialsProvider(MY-CUSTOM-CREDENTIAL-PROVIDER, "MY-AWS-REGION", applicationContext)

    var geoMapsClient = GeoMapsClient(authHelper?.getGeoMapsClientConfig())
    var geoPlacesClient = GeoPlacesClient(authHelper?.getGeoPlacesClientConfig())
    var geoRoutesClient = GeoRoutesClient(authHelper?.getGeoRoutesClientConfig())
    
    var locationClient = LocationClient(authHelper?.getLocationClientConfig())
}
```

**Example: Credential Provider with API Key**

```
private suspend fun exampleApiKeyLogin() {
    var authHelper = AuthHelper.withApiKey("MY-API-KEY", "MY-AWS-REGION", applicationContext)

    var geoMapsClient = GeoMapsClient(authHelper?.getGeoMapsClientConfig())
    var geoPlacesClient = GeoPlacesClient(authHelper?.getGeoPlacesClientConfig())
    var geoRoutesClient = GeoRoutesClient(authHelper?.getGeoRoutesClientConfig())
    
    var locationClient = LocationClient(authHelper?.getLocationClientConfig())
}
```

You can use `LocationCredentialsProvider` to load the MapLibre map. Here is an example:

```
HttpRequestUtil.setOkHttpClient(
    OkHttpClient.Builder()
        .addInterceptor(
            AwsSignerInterceptor(
                "geo",
                "MY-AWS-REGION",
                locationCredentialsProvider,
                applicationContext
            )
        )
        .build()
)
```

Use the created clients to make calls to Amazon Location Service. Here is an example that searches for places near a specified latitude and longitude:

```
val suggestRequest = SuggestRequest {
       biasPosition = listOf(-97.718833, 30.405423)
       maxResults = MAX_RESULT
       language = "PREFERRED-LANGUAGE"
   }
val nearbyPlaces = geoPlacesClient.suggest(suggestRequest)
```

# Use Amazon Location MapLibre Geocoder GL plugin
<a name="dev-maplibre-geocoder"></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
<a name="geocoder-installation"></a>

Install Amazon Location MapLibre geocoder plugin from NPM for usage with modules. Type this command:

```
npm install @aws/amazon-location-for-maplibre-gl-geocoder
```

You can also import HTML and CSS files for usage directly in the browser with a script:

```
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-for-maplibre-gl-geocoder@2"></script>
<link
  href="https://cdn.jsdelivr.net/npm/@aws/amazon-location-for-maplibre-gl-geocoder@2/dist/amazon-location-for-mlg-styles.css"
  rel="stylesheet"
/>
```

## Usage with module - standalone GeoPlaces SDK
<a name="geocoder-module"></a>

This example uses the [AWS SDK for JavaScript V3](https://github.com/aws/aws-sdk-js-v3) to get a GeoPlacesClient to provide to the library and [AuthHelper](https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js) for authenticating the GeoPlacesClient. It enables all APIs for the geocoder.

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

const apiKey = "<API Key>";
const mapName = "Standard";
const region = "<Region>"; // region containing Amazon Location API Key

// Create an authentication helper instance using an API key and region
const authHelper = await withAPIKey(apiKey, region);

const client = new GeoPlacesClient(authHelper.getClientConfig());

// Render the map
const map = new maplibregl.Map({
  container: "map",
  center: [-123.115898, 49.295868],
  zoom: 10,
  style: `https://maps.geo.${region}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${apiKey}`,
});

// Gets an instance of the AmazonLocationMaplibreGeocoder Object.
const amazonLocationMaplibreGeocoder = buildAmazonLocationMaplibreGeocoder(client, { enableAll: true });

// Now we can add the Geocoder to the map.
map.addControl(amazonLocationMaplibreGeocoder.getPlacesGeocoder());
```

## Usage with a browser - standalone GeoPlaces SDK
<a name="geocoder-browser"></a>

This example uses the Amazon Location client to make a request that authenticates using an API key.

**Note**  
Some of these example use the Amazon Location GeoPlacesClient. This 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 For Maplibre Geocoder -->
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-for-maplibre-gl-geocoder@2"></script>
<link
  href="https://cdn.jsdelivr.net/npm/@aws/amazon-location-for-maplibre-gl-geocoder@2/dist/amazon-location-for-mlg-styles.css"
  rel="stylesheet"
/>
<!-- Import the Amazon GeoPlacesClient -->
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1"></script>
```

Include the following in a JavaScript file:

```
const apiKey = "<API Key>";
const mapStyle = "Standard";
const region = "<Region>"; // region containing Amazon Location API key

// Create an authentication helper instance using an API key and region
const authHelper = await amazonLocationClient.withAPIKey(apiKey, region);

const client = new amazonLocationClient.GeoPlacesClient(authHelper.getClientConfig());

// Render the map
const map = new maplibregl.Map({
  container: "map",
  center: [-123.115898, 49.295868],
  zoom: 10,
  style: `https://maps.geo.${region}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${apiKey}`,
});

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

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

## Functions
<a name="geocoder-functions"></a>

Listed below are the functions 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.

  Using standalone `GeoPlacesClient` API calls (client is instance of `GeoPlacesClient`):

  ```
  const amazonLocationMaplibreGeocoder = buildAmazonLocationMaplibreGeocoder(client, { enableAll: true });
  ```

  Using consolidated `LocationClient` API calls (client is instance of `LocationClient`):

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

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

  ```
  const geocoder = getPlacesGeocoder();
  
  // Initialize map see: <insert link to initializing a map instance here>
  let map = await initializeMap();
  
  // Add the geocoder to the map.
  map.addControl(geocoder);
  ```

# How to use Tracking SDKs
<a name="dev-tracking-sdk"></a>

This topic provides information about how to use Tracking SDKs.

# iOS
<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 Amazon 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)
    }
})
}
```

# 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 Amazon 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()
```

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

[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 or 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.

  For more information, see [Use Amazon Location MapLibre Geocoder GL plugin](dev-maplibre-geocoder.md).
+ **Routes**
+ **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 convert responses into GeoJSON for use in JavaScript applications. For more information, see [SDKs and frameworks for Amazon Location Service](dev-sdks.md). 

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

**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.

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

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

The following AWS SDKs and Map Rendering Framework versions are available for web frontend application development.


| Language / Framework | AWS SDK | Map 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/)  | [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native) [https://www.npmjs.com/package/@maplibre/maplibre-gl-native](https://www.npmjs.com/package/@maplibre/maplibre-gl-native) | 
|  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 Map Rendering Framework versions are available for mobile frontend application development.


| Language / Framework | AWS SDK | Map 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. Map Rendering Frameworks are 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.  | 

------

# Map Rendering SDK by language
<a name="map-rendering-by-language"></a>

We recommend rendering Amazon Location Service 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 interfaces for searching and routes in some languages and platforms. 

To learn more about using MapLibre and the functionality it provides, see [Use MapLibre tools and related libraries with Amazon Location](dev-maplibre.md) and [How to use dynamic maps](dynamic-maps-how-to.md). 

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

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

The following Map Rendering SDKs are available for web frontend application development.


| Language / Framework | Map Rendering Framework | 
| --- | --- | 
|  **Fully supported**  | 
|  JavaScript  |  [https://github.com/maplibre/maplibre-gl-js](https://github.com/maplibre/maplibre-gl-js)  | 
|  ReactJS  |  [https://github.com/maplibre/maplibre-react-native](https://github.com/maplibre/maplibre-react-native)  | 
|  TypeScript  |  [https://github.com/maplibre/maplibre-gl-js](https://github.com/maplibre/maplibre-gl-js)  | 
|  **Partially supported**  | 
|  Flutter  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) The MapLibre Flutter library is considered experimental.  | 
|  Node.js  |   There is no MapLibre support for Node.js.  | 
|  PHP  |   There is no MapLibre support for PHP.  | 

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

The following Map Rendering SDKs are available for mobile frontend application development.


| Language / Framework | Map Rendering Framework | 
| --- | --- | 
|  **Fully supported**  | 
|  Java  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native)  | 
|  Kotlin  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native) Requires custom bindings, as MapLibre is Java-based.  | 
|  ObjectiveC  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native)  | 
|  ReactNative  |  [https://github.com/maplibre/maplibre-react-native](https://github.com/maplibre/maplibre-react-native)  | 
|  Swift  |  [https://github.com/maplibre/maplibre-native](https://github.com/maplibre/maplibre-native)  | 
|  **Partially supported**  | 
|  Flutter  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) The MapLibre Flutter library is considered experimental.  | 

------

# Address Form SDK
<a name="address-form-sdk"></a>

The Address Form SDK streamlines building smart address-entry forms. Address forms built with the SDK provide relevant address suggestions as users begin typing. When a user selects a suggestion, an address form automatically fills in fields such as city, state, and postal code. This reduces errors and speeds up data entry by minimizing manual input. Users can also preview the selected address on a map and adjust its location pin to indicate specific entrances or pick-up locations, significantly improving accuracy.

![\[Address Form SDK demonstration showing autocomplete functionality\]](http://docs.aws.amazon.com/location/latest/developerguide/images/address-form-demo.gif)


## Try It
<a name="address-form-try-it"></a>

### Demo
<a name="address-form-demo"></a>

Try the fully functional [address form demo](https://aws-geospatial.github.io/address-form-sdk-js/). 

### Build It Yourself
<a name="address-form-builder"></a>

Jump to [Getting Started](#address-form-getting-started) to begin implementing address forms using the Address Form SDK, or try the no-code approach with the Location Service’s WYSIWYG [Address Form Builder wizard](https://console.aws.amazon.com/location/solution-builder/home#/address-form), powered by this SDK and accessible in the Amazon Location Service console at [https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/). This interactive wizard lets you create customized forms with predictive suggestions, automatic field population, and flexible layouts. Developers can download ready-to-use packages in React JavaScript, React TypeScript, or standalone HTML/JavaScript for easy integration without writing any code.

## Key Features
<a name="address-form-features"></a>

Key features of the Address Form SDK include:
+ Provides built-in typeahead suggestions for addresses and POIs, speeding up data entry.
+ Enables configurable place-type search (e.g., postal codes, localities) for more precise results.
+ Offers automatic browser location detection to quickly center users on their current area.
+ Displays built-in map visualizations for greater clarity and context.
+ Allows address locations to be adjusted on the map without losing the system-provided location, ensuring both accuracy and control.
+ Includes a WYSIWYG builder tool that requires no coding, saving time and effort.
+ Implements debouncing and caching for typeahead APIs to optimize performance and reduce costs.
+ Supports style customization to match your application's brand and user experience.

It uses the following Amazon Location Service API operations to provide address information to address forms:

**[GetTile](https://docs.aws.amazon.com/location/latest/APIReference/API_geomaps_GetTile.html)**  
Retrieves map tiles for rendering the interactive map to visualize the location of the address and adjust the position of an address.

**[Autocomplete](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Autocomplete.html)**  
Provides real-time address suggestions as users type.

**[Suggest](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Suggest.html)**  
Provides real-time address and POI suggestions as users type.

**[ReverseGeocode](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_ReverseGeocode.html)**  
Converts a user's current location to the nearest known address address if they choose to auto-fill their address based on their current location.

**[GetPlace](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_GetPlace.html)**  
Retrieves detailed place information for selected addresses after selecting an address from the results of the Autocomplete or Suggest API.

## Pricing
<a name="address-form-pricing"></a>

The SDK is free and [open sourced](https://github.com/aws-geospatial/address-form-sdk-js) under the Apache-2.0 license. You only pay for API usage. Please consult the [Amazon Location Service pricing page](https://aws.amazon.com/location/pricing/).

## Getting Started
<a name="address-form-getting-started"></a>

The Address Form SDK can be used within a React app or in a standalone HTML and JavaScript page. Get started by following the instructions below.

### Prerequisites
<a name="address-form-prerequisites"></a>

**Note**  
The Address Form SDK requires an API key with the required permissions to work properly. Create an API key with the following permissions using the [Address Form SDK Builder wizard](https://console.aws.amazon.com/location/solution-builder/home#/address-form) in Amazon Location Service console, or follow the instructions below to create it manually.

Use of the Address Form SDK requires the following actions to be allowed in the API key policy:
+ `geo-maps:GetTile` - This is required when displaying the map component. See the [GetTile](https://docs.aws.amazon.com/location/latest/APIReference/API_geomaps_GetTile.html) API reference.
+ `geo-places:Autocomplete` - This is required when using the `Autocomplete` operation for typeahead functionality. See the [Autocomplete](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Autocomplete.html) API reference.
+ `geo-places:Suggest` - This is required when using the `Suggest` operation for typeahead functionality. See the [Suggest](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Suggest.html) API reference.
+ `geo-places:ReverseGeocode` - This is required when allowing users to provide their current location using browsers' geolocation API. See the [ReverseGeocode](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_ReverseGeocode.html) API reference.
+ `geo-places:GetPlace` - This is required when using the typeahead functionality. See the [GetPlace](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_GetPlace.html) API reference.

Follow the [Use API Keys to authenticate](https://docs.aws.amazon.com/location/latest/developerguide/using-apikeys.html) guide to create an Amazon Location Service API key with the necessary permissions.

Example key policy for the [CreateKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_CreateKey.html) API with required permissions:

#### CreateKey request for Address Form permissions
<a name="createkey-example"></a>

```
{
  "KeyName": "ExampleKey",
  "ExpireTime": "YYYY-MM-DDThh:mm:ss.sss",
  "Restrictions": {
    "AllowActions": [
      "geo-maps:GetTile",
      "geo-places:Autocomplete",
      "geo-places:Suggest",
      "geo-places:GetPlace",
      "geo-places:ReverseGeocode"
    ],
    "AllowResources": [
      "arn:aws:geo-maps:<Region>::provider/default",
      "arn:aws:geo-places:<Region>::provider/default"
    ]
  }
}
```

### Installation
<a name="address-form-installation"></a>

#### HTML/JavaScript
<a name="address-form-html-js-install"></a>

Include the following CSS and JavaScript for the SDK in your HTML code

```
...
<head>
...
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@aws/address-form-sdk-js/dist/standalone/address-form-sdk.css"
/>
...
</head>
...
<body>
...
<script src="https://cdn.jsdelivr.net/npm/@aws/address-form-sdk-js/dist/standalone/address-form-sdk.umd.js"></script>
</body>
...
```

#### React
<a name="address-form-react-install"></a>

Install the SDK from npm: `npm install @aws/address-form-sdk-js`

### Use the SDK
<a name="address-form-use-sdk"></a>

Add the following code to your React app. Update `AMAZON_LOCATION_API_KEY` with your API key and `AMAZON_LOCATION_REGION` with the region where the API key was created. When the form is submitted, the `onSubmit` callback provides a `getData` async function. Call this function with an `intendedUse` value to retrieve the form data.

```
onSubmit: async (getData) => {
  const data = await getData({
    intendedUse: "SingleUse", // or "Storage"
  });
};
```

**Note**  
Use `"Storage"` if you need to store or cache the results. This ensures compliance with Amazon Location Service [intended use requirements](https://docs.aws.amazon.com/location/latest/developerguide/places-intended-use.html).

------
#### [ HTML/JavaScript ]

```
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Address Form</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@aws/address-form-sdk-js/dist/standalone/address-form-sdk.css"
    />
  </head>
  <body>
    <form
      id="amazon-location-address-form"
      class="address-form flex-row flex-1"
    >
      <div class="flex-column">
        <input
          data-type="address-form"
          name="addressLineOne"
          data-api-name="suggest"
          data-show-current-location="true"
        />
        <input data-type="address-form" name="addressLineTwo" />
        <input data-type="address-form" name="city" />
        <input data-type="address-form" name="province" />
        <input data-type="address-form" name="postalCode" />
        <input data-type="address-form" name="country" />
        <div class="flex-row">
          <button data-type="address-form" type="submit">Submit</button>
          <button data-type="address-form" type="reset">Reset</button>
        </div>
      </div>
      <div data-type="address-form" data-map-style="Standard,Light"></div>
    </form>
    <></script>
script src="https://cdn.jsdelivr.net/npm/@aws/address-form-sdk-js/dist/standalone/address-form-sdk.umd.js"
    <script>
      AddressFormSDK.render({
        root: "#amazon-location-address-form",
        apiKey: "AMAZON_LOCATION_API_KEY",
        region: "AMAZON_LOCATION_REGION",
        showCurrentCountryResultsOnly: true,
        onSubmit: async (getData) => {
          // Get form data with intendedUse parameter
          // Use "SingleUse" for one-time display only
          // Use "Storage" if you plan to store/cache the results - makes an extra API call to grant storage rights
          const data = await getData({ intendedUse: "SingleUse" });
          console.log(data);
        },
      });
    </script>
  </body>
</html>
```

------
#### [ React ]

```
import React from 'react';
import { AddressForm, Flex } from "@aws/address-form-sdk-js";

export default function App() {
  return (
    <AddressForm
      apiKey="AMAZON_LOCATION_API_KEY"
      region="AMAZON_LOCATION_REGION"
      onSubmit={async (getData) => {
        // Get form data with intendedUse parameter
        // Use "SingleUse" for one-time display only
        // Use "Storage" if you plan to store/cache the results - makes an extra API call to grant storage rights
        const data = await getData({ intendedUse: "SingleUse" });
        console.log(data);
      }}
    >
      <Flex
        direction="row"
        flex
      >
        <Flex direction="column">
          <input
            data-api-name="autocomplete"
            data-type="address-form"
            name="addressLineOne"
            placeholder="Enter address"
          />
          <input
            data-type="address-form"
            name="addressLineTwo"
          />
          <input
            data-type="address-form"
            name="city"
            placeholder="City"
          />
          <input
            data-type="address-form"
            name="province"
            placeholder="State/Province"
          />
          <input
            data-type="address-form"
            name="postalCode"
          />
          <input
            data-type="address-form"
            name="country"
            placeholder="Country"
          />
          <Flex direction="row">
            <button address-form="submit">
              Submit
            </button>
            <button address-form="reset">
              Reset
            </button>
          </Flex>
        </Flex>
        <AddressFormMap
          mapStyle={[
            'Standard',
            'Light'
          ]}
         />
      </Flex>
    </AddressForm>
  );
}
```

------

## Supported Countries
<a name="address-form-supported-countries"></a>

The Address Form SDK supports auto-filling addresses globally using Amazon Location Service. The following countries have full support with address field parsing, where each address component is populated into its respective field:
+ Australia (AU)
+ Canada (CA)
+ France (FR)
+ Hong Kong (HK)
+ Ireland (IE)
+ New Zealand (NZ)
+ Philippines (PH)
+ Singapore (SG)
+ United Kingdom (GB)
+ United States (US)

All other countries are in Preview status. Preview countries display the complete address in `addressLineOne` field without country-specific formatting. Future releases will improve this behavior and you can access these improvements by using the latest version of the SDK.

## Supported AWS Regions
<a name="address-form-supported-aws-regions"></a>

The Address Form SDK and Address Form Builder wizard are available in all AWS regions where Amazon Location Service operates, using the `Current` version of its APIs. View the complete list of supported regions in [Amazon Location supported regions](https://docs.aws.amazon.com/location/latest/developerguide/location-regions.html).

## API Reference
<a name="address-form-api-reference"></a>

Refer to [README API Reference](https://github.com/aws-geospatial/address-form-sdk-js#api-reference).