

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# SDKs 以及 Amazon Location Service 的框架
<a name="dev-sdks"></a>

AWS 提供适用于多种编程语言的软件开发套件 (SDKs)，使您可以轻松地将 Amazon Location Service 集成到您的应用程序中。本页概述了可用的 SDKs软件及其安装过程和代码示例，以帮助您在首选的开发环境中开始使用 Amazon Location Service。

有几种工具可以帮助您使用 Amazon Location Service。
+ **AWS SDKs**— AWS 软件开发套件 (SDKs) 提供多种常用编程语言版本，提供了 API、代码示例和文档，可让您更轻松地使用首选语言构建应用程序。 AWS SDKs 包括 Amazon 的核心位置 APIs 和功能，包括访问地图、地点、路线、地理围栏和追踪器。要详细了解 SDKs 可用于不同应用程序和语言的 Amazon Location Service，请参阅[按语言划分的 SDK](dev-by-language.md)。
+ **MapLibre**— Amazon Location Service 建议使用[MapLibre](https://github.com/maplibre/maplibre-gl-js)渲染引擎渲染地图。 MapLibre 是用于在 Web 或移动应用程序中显示地图的引擎。 MapLibre 还具有插件模型，并支持某些语言和平台的用户界面进行搜索和路由。要了解有关使用 MapLibre 及其提供的功能的更多信息，请参阅[将 MapLibre 工具和相关库与 Amazon Location 结合使用](dev-maplibre.md)。
+ **Amazon Loc** ation SDKs — Amazon Loc SDKs ation 是一组开源库，可以更轻松地使用 Amazon Location Service 开发应用程序。这些库提供了支持移动和网络应用程序身份验证、移动应用程序位置跟踪、亚马逊位置数据类型与 [GeoJSON](https://geojson.org/) 之间的转换以及适用于 S AWS DK v3 的 Amazon Location 客户端托管包的功能。要了解有关 Amazon 营业地点的更多信息 SDKs，请参阅[按语言划分的 SDK](dev-by-language.md)。
+ **Amazon Location Migration SDK** – Amazon Location Migration SDK 提供一个使您能够将现有应用程序从 Google 地图迁移到 Amazon Location 的桥梁。如果 Amazon Location 支持所使用的功能，迁移软件开发工具包为您使用 Google Maps SDK 构建的应用程序提供了一个使用亚马逊定位服务的选项，无需重写任何应用程序或业务逻辑。 JavaScript 该 Migration SDK 会将所有 API 调用重定向到 Amazon Location，而不是 Google Map。要开始使用，请参阅上的 [Amazon 位置迁移软件开发工具包](https://github.com/aws-geospatial/amazon-location-migration) GitHub。

# 开发人员教程
<a name="sdk-how-to"></a>

要了解如何使用 Amazon Location Service SDK 的各个方面，请参阅本节内容。

**Topics**
+ [如何使用身份验证帮助程序](how-to-auth-helper.md)
+ [使用 Amazon 位置 MapLibre 地理编码器 GL 插件](dev-maplibre-geocoder.md)
+ [如何使用跟踪 SDK](dev-tracking-sdk.md)
+ [将 MapLibre 工具和相关库与 Amazon Location 结合使用](dev-maplibre.md)

# 如何使用身份验证帮助程序
<a name="how-to-auth-helper"></a>

本节提供有关身份验证帮助程序的其他信息。

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

当从 JavaScript 应用程序调用 Amazon Location Service API 时，亚马逊位置 JavaScript 认证实用程序可帮助进行身份验证。这些实用程序专门支持使用 API 密钥或 Amazon Cognito 进行身份验证。

**安装**
+ 使用 NPM 安装此库：

  ```
  npm install @aws/amazon-location-utilities-auth-helper
  ```
+ 要直接在浏览器中使用它，请在您的 HTML 文件中包含以下内容：

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

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

要使用身份验证帮助程序，请导入该库，然后调用必要的实用程序函数。该库支持对来自 Amazon Location Ser SDKs vice（包括独立[地图](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-maps/)、[地点](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-places/)和[路线](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-routes/)）的请求进行身份验证 SDKs，也支持使用 [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js) 渲染地图。

**与模块配合使用**

本示例演示了如何使用独立的地点 SDK 发出使用 API 密钥进行身份验证的请求：

```
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);
```

本示例演示了如何使用独立的路线 SDK 发出使用 API 密钥进行身份验证的请求：

```
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);
```

本示例将 Location SDK 与 API 密钥身份验证结合使用：

```
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);
```

**与浏览器配合使用**

当直接在浏览器环境中使用时，可以在 amazonLocationAuth Helper 全局对象下访问实用函数。

本示例演示了通过 Amazon Location 客户端发出的使用 API 密钥进行身份验证的请求：

```
<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);
```

此示例演示了使用 MapLibre GL JS 渲染地图，并使用 API 密钥进行身份验证：

```
<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}`,
});
```

此示例演示如何使用 Amazon Cognito 使用 MapLibre GL JS 渲染地图：

```
<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(),
});
```

**经过验证的身份的替代用法**

您可以修改 withIdentityPool Id 函数以包含经过身份验证的身份的自定义参数：

```
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>

适用于 iOS 的 Amazon Location Service 移动身份验证 SDK 可帮助验证来 APIs 自 iOS 应用程序的亚马逊定位服务请求。它专门支持通过 API 密钥或 Amazon Cognito 进行身份验证。

**安装**
+ 打开 Xcode，然后转到**文件 > 添加程序包依赖项**。
+ 在搜索栏中键入软件包网址 ([https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/))，然后按 Enter。
+ **选择 “amazon-location-mobile-auth-sdk-ios” 软件包，然后单击 “添加包”。**
+ 选择 “AmazonLocationiOSAuthSDK” 套餐产品，然后单击 **Add Packag** e。

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

安装库后，使用 `AuthHelper` 类为 API 密钥或 Amazon Cognito 配置客户端设置。

**API 密钥**

下面是将独立的地点 SDK 与 API 密钥身份验证结合使用的示例：

```
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)
}
```

下面是将独立的路线 SDK 与 API 密钥身份验证结合使用的示例：

```
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)
}
```

下面是将 Location SDK 与 API 密钥身份验证结合使用的示例：

```
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)
}
```

下面是将独立的地点 SDK 与 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)
}
```

下面是将独立的路线 SDK 与 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)
}
```

下面是将 Location SDK 与 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>

适用于 Android 的 Amazon Location Service 移动身份验证 SDK 可帮助您对 APIs 来自安卓应用程序的亚马逊定位服务请求进行身份验证，特别是支持使用 Amazon Cognito 进行身份验证。

**安装**
+ 此身份验证 SDK 可与整个 K AWS otlin SDK 配合使用。两者 SDKs 都发布到 Maven Central。在 Maven Central 上检查[身份验证 SDK](https://mvnrepository.com/artifact/software.amazon.location/auth) 的最新版本。
+ 在 Android Studio 中将以下几行添加到 `build.gradle` 文件的依赖项部分：

  ```
  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")
  ```
+ 对于独立地图、地点和路线 SDKs，请添加以下几行：

  ```
  implementation("aws.sdk.kotlin:geomaps:1.3.65")
  implementation("aws.sdk.kotlin:geoplaces:1.3.65")
  implementation("aws.sdk.kotlin:georoutes:1.3.65")
  ```
+ 对于包含地理围栏和跟踪功能的合并 Location SDK，请添加以下行：

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

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

在您的代码中导入以下类：

```
// 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
```

你可以创建一个`AuthHelper`并将其与 AWS Kotlin SDK 配合使用：

**示例：具有身份池 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())
}
```

**示例：具有自定义凭证提供程序的凭证提供程序**

```
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())
}
```

**示例：具有 API 密钥的凭证提供程序**

```
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())
}
```

您可以使用`LocationCredentialsProvider`来加载 MapLibre 地图。示例如下：

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

使用创建的客户端来调用 Amazon Location Service。以下示例搜索指定纬度和经度附近的地点：

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

# 使用 Amazon 位置 MapLibre 地理编码器 GL 插件
<a name="dev-maplibre-geocoder"></a>

Amazon Location MapLibre 地理编码器插件旨在让您在使用库进行地图渲染和地理编码时更轻松地将 Amazon Location 功能整合到 JavaScript 应用程序中。[maplibre-gl-geocoder](https://github.com/maplibre/maplibre-gl-geocoder)

## 安装
<a name="geocoder-installation"></a>

安装来自 NPM 的 Amazon Location MapLibre 地理编码器插件，以便与模块一起使用。键入以下命令：

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

您也可以使用以下脚本导入 HTML 和 CSS 文件，以便直接在浏览器中使用：

```
<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"
/>
```

## 与模块一起使用-独立 GeoPlaces SDK
<a name="geocoder-module"></a>

此示例使用[AWS 适用于 JavaScript V3 的 SDK](https://github.com/aws/aws-sdk-js-v3) 来获取 GeoPlacesClient 要提供给库的，并[AuthHelper](https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js)对库进行身份验证。 GeoPlacesClient它 APIs 为地理编码器启用了所有功能。

```
// 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());
```

## 在浏览器中使用-独立 GeoPlaces SDK
<a name="geocoder-browser"></a>

此示例使用 Amazon Location 客户端发出通过 API 密钥进行身份验证的请求。

**注意**  
其中一些示例使用了 Amazon 地点 GeoPlacesClient。此客户端基于[AWS 适用于 JavaScript V3 的软件开发工具包](https://github.com/aws/aws-sdk-js-v3)，允许通过 HTML 文件中引用的脚本调用 Amazon Location。

在 HTML 文件中包含以下内容：

```
<!-- 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>
```

在 JavaScript 文件中包含以下内容：

```
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());
```

## 函数
<a name="geocoder-functions"></a>

下面列出了 Amazon Location MapLibre 地理编码器插件中使用的函数：
+ `buildAmazonLocationMaplibreGeocoder`

  该类创建 `AmazonLocationMaplibreGeocder` 的一个实例，此实例是其他所有调用的入口点。

  使用独立的 `GeoPlacesClient` API 调用（客户端是 `GeoPlacesClient` 的实例）：

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

  使用整合的 `LocationClient` API 调用（客户端是 `LocationClient` 的实例）：

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

  返回可以直接添加到地图的 ready-to-use IControl 对象。

  ```
  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);
  ```

# 如何使用跟踪 SDK
<a name="dev-tracking-sdk"></a>

本主题提供了有关如何使用跟踪 SDK 的信息。

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

Amazon Location 移动跟踪 SDK 提供的实用程序可帮助您轻松进行身份验证、捕获设备位置以及向 Amazon Location 跟踪器发送位置更新。该 SDK 支持通过可配置的更新间隔对位置更新进行本地筛选。这样可以降低数据成本，并优化 iOS 应用程序的间歇性连接。

iOS 追踪软件开发工具包可在以下网址获得 GitHub：适用于 [iOS 的亚马逊定位移动追踪软件开发工具包](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios)。

本节涵盖 Amazon Location 移动跟踪 iOS SDK 的以下主题：

**Topics**
+ [安装](#loc-mobile-tracking-install-ios)
+ [用法](#loc-mobile-tracking-usage-ios)
+ [筛选条件](#loc-mobile-tracking-ios-filters)
+ [iOS 移动 SDK 跟踪函数](#loc-mobile-tracking-functions)
+ [示例](#loc-mobile-tracking-example-ios)

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

使用以下步骤安装适用于 iOS 的移动跟踪 SDK：

1. 在您的 Xcode 项目中，转到**文件**，然后选择**添加软件包依赖项**。

1. 在搜索栏中键入以下 URL：[https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios/](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-ios/)，然后按回车键。

1. 选择 `amazon-location-mobile-tracking-sdk-ios` 软件包并单击**添加软件包**。

1. 选择 `AmazonLocationiOSTrackingSDK` 软件包产品并单击**添加软件包**。

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

以下步骤介绍了如何从 Amazon Cognito 中使用凭证创建身份验证帮助程序。

1. 安装库后，需要在 `info.plist` 文件中添加一个或两个描述：

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

1. 接下来， AuthHelper 在你的课堂中导入：

   ```
   import AmazonLocationiOSAuthSDKimport AmazonLocationiOSTrackingSDK
   ```

1. 然后，您将使用来自 Amazon Cognito 的凭证创建身份验证助手，从而创建一个`AuthHelper`对象并将其与 AWS 软件开发工具包一起使用。

   ```
   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)
   ```

## 筛选条件
<a name="loc-mobile-tracking-ios-filters"></a>

Amazon Location 移动跟踪 iOS SDK 有三个内置的位置筛选器。
+ `TimeLocationFilter`：根据定义的时间间隔筛选要上传的当前位置。
+ `DistanceLocationFilter`：根据指定的距离阈值筛选位置更新。
+ `AccuracyLocationFilter`：通过将自上次更新以来移动的距离与当前位置的精度进行比较来筛选位置更新。

此示例在创建时在 `LocationTracker` 中添加筛选器：

```
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,
)
```

此示例在运行时使用 `LocationTracker` 启用和禁用筛选器：

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

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

## iOS 移动 SDK 跟踪函数
<a name="loc-mobile-tracking-functions"></a>

适用于 iOS 的 Amazon Location 移动跟踪 SDK 包括以下函数：
+ **类**：`LocationTracker`

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

  这是用于创建 `LocationTracker` 对象的初始化程序函数。它需要 `LocationCredentialsProvider`、`trackerName` 的实例，以及（可选）`LocationTrackingConfig` 的实例。如果未提供配置，将使用默认值对其进行初始化。
+ **类**：`LocationTracker`

  `setTrackerConfig(config: LocationTrackerConfig)`

  它将跟踪器的配置设置为在位置跟踪器初始化后的任何时候生效。
+ **类**：`LocationTracker`

  `getTrackerConfig()`

  它将获取要在您的应用程序中使用或修改的位置跟踪配置。

  返回：`LocationTrackerConfig`
+ **类**：`LocationTracker`

  `getDeviceId()`

  获取位置跟踪器生成的设备 ID。

  返回：`String?`
+ **类**：`LocationTracker`

  `startTracking()`

  启动访问用户位置并将其发送到 AWS 跟踪器的过程。
+ **类**：`LocationTracker`

  `resumeTracking()`

  恢复访问用户位置并将其发送到 AWS 跟踪器的过程。
+ **类**：`LocationTracker`

  `stopTracking()`

  停止跟踪用户位置的过程。
+ **类**：`LocationTracker`

  `startBackgroundTracking(mode: BackgroundTrackingMode)`

  启动访问用户位置的过程，并在应用程序处于后台时将其发送到 AWS 跟踪器。 `BackgroundTrackingMode`有以下选项：
  + `Active:` 此选项不会自动暂停位置更新。
  + `BatterySaving:` 此选项自动暂停位置更新。
  + `None:` 此选项总体上禁用后台位置更新。
+ **类**：`LocationTracker`

  `resumeBackgroundTracking(mode: BackgroundTrackingMode)`

  当应用程序处于后台时，恢复访问用户位置并将其发送到 AWS 跟踪器的过程。
+ **类**：`LocationTracker`

  `stopBackgroundTracking()`

  当应用程序处于后台时，停止访问用户位置并将其发送到 AWS 跟踪器的过程。
+ **类**：`LocationTracker`

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

  在开始和结束日期和时间之间检索为用户设备上传的跟踪位置。

  返回：`Void`
+ **类**：`LocationTrackerConfig`

  `init()`

  这将 LocationTrackerConfig 使用默认值初始化。
+ **类**：`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)`

  它使用用户定义的参数值初始化 `LocationTrackerConfig`。如果未提供参数值，会将其设置为默认值。
+ **类**：`LocationFilter`

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

  `LocationFilter` 是用户可以为其自定义筛选器实现实施的协议。用户需要实现 `shouldUpload` 函数来比较以前和当前的位置，并返回是否应该上传当前位置。

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

本节详细介绍了使用适用于 iOS 的 Amazon Location 移动跟踪 SDK 的示例。

**注意**  
确保在 `info.plist` 文件中设置了必要的权限。这些权限与 [用法](#loc-mobile-tracking-usage-ios) 部分中列出的权限相同。

以下示例演示了跟踪设备位置和检索跟踪位置的功能：

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

开始跟踪位置：

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

恢复跟踪位置：

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

停止跟踪位置：

```
locationTracker.stopTracking()
```

开始后台跟踪：

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

恢复后台跟踪：

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

停止后台跟踪：

```
locationTracker.stopBackgroundTracking()
```

从跟踪器检索设备的跟踪位置：

```
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 移动跟踪 SDK
<a name="loc-mobile-tracking-android"></a>

Amazon Location 移动跟踪 SDK 提供的实用程序可帮助您轻松进行身份验证、捕获设备位置以及向 Amazon Location 跟踪器发送位置更新。该 SDK 支持通过可配置的更新间隔对位置更新进行本地筛选。这样可以降低数据成本，优化 Android 应用程序的间歇性连接。

Android 追踪 SDK 可在以下网址获得 GitHub：[适用于安卓的亚马逊定位移动追踪 SDK](https://github.com/aws-geospatial/amazon-location-mobile-tracking-sdk-android)。此外，M [AWS aven 存储库](https://central.sonatype.com/artifact/software.amazon.location/tracking)中还提供了移动身份验证 AWS SDK 和 SDK。Android 追踪 SDK 专为与通用 AWS SDK 配合使用而设计。

本节涵盖 Amazon Location 移动跟踪 Android SDK 的以下主题：

**Topics**
+ [安装](#loc-mobile-tracking-install-android)
+ [用法](#loc-mobile-tracking-usage-android)
+ [筛选条件](#loc-mobile-tracking-android-filters)
+ [Android 移动 SDK 跟踪函数](#loc-mobile-tracking-functions)
+ [示例](#loc-mobile-tracking-example-android)

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

要安装该 SDK，请在 Android Studio 中将以下几行添加到 build.gradle 文件的依赖项部分：

```
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")
```

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

以下步骤展示了如何使用该 SDK 进行身份验证和创建 `LocationTracker` 对象：

**注意**  
以下步骤假设已经导入[安装](#loc-mobile-tracking-install-android)部分中提到的库。

1. 在您的代码中导入以下类：

   ```
   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. 接下来，创建一个 `AuthHelper`，因为创建 `LocationTracker` 对象需要 `LocationCredentialsProvider` 参数：

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

1. 现在，使用 `LocationCredentialsProvider` 和 `LocationTrackerConfig` 创建 `LocationTracker` 对象：

   ```
   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,
   )
   ```

## 筛选条件
<a name="loc-mobile-tracking-android-filters"></a>

Amazon Location 移动跟踪 Android SDK 有三个内置的位置筛选器。
+ `TimeLocationFilter`：根据定义的时间间隔筛选要上传的当前位置。
+ `DistanceLocationFilter`：根据指定的距离阈值筛选位置更新。
+ `AccuracyLocationFilter`：通过将自上次更新以来移动的距离与当前位置的精度进行比较来筛选位置更新。

此示例在创建时在 `LocationTracker` 中添加筛选器：

```
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,
)
```

此示例在运行时使用 `LocationTracker` 启用和禁用筛选器：

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

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

## Android 移动 SDK 跟踪函数
<a name="loc-mobile-tracking-functions"></a>

适用于 Android 的 Amazon Location 移动跟踪 SDK 包括以下函数：
+ **类**：`LocationTracker`

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

  这是用于创建 `LocationTracker` 对象的初始化程序函数。它需要 `LocationCredentialsProvider`、`trackerName` 的实例，以及（可选）`LocationTrackingConfig` 的实例。如果未提供配置，将使用默认值对其进行初始化。
+ **类**：`LocationTracker`

  `start(locationTrackingCallback: LocationTrackingCallback)`

  启动访问用户位置并将其发送到 Amazon Location 跟踪器的过程。
+ **类**：`LocationTracker`

  `isTrackingInForeground()`

  检查当前是否正在进行位置跟踪。
+ **类**：`LocationTracker`

  `stop()`

  停止跟踪用户位置的过程。
+ **类**：`LocationTracker`

  `startTracking()`

  启动访问用户位置并将其发送到 AWS 跟踪器的过程。
+ **类**：`LocationTracker`

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

  启动访问用户位置的过程，并在应用程序处于后台时将其发送到 AWS 跟踪器。 `BackgroundTrackingMode`有以下选项：
  + `ACTIVE_TRACKING`：此选项主动跟踪用户的位置更新。
  + `BATTERY_SAVER_TRACKING`：此选项每 15 分钟跟踪一次用户的位置更新。
+ **类**：`LocationTracker`

  `stopBackgroundService()`

  当应用程序处于后台时，停止访问用户位置并将其发送到 AWS 跟踪器的过程。
+ **类**：`LocationTracker`

  `getTrackerDeviceLocation()`

  从 Amazon Location Service 检索设备位置。
+ **类**：`LocationTracker`

  `getDeviceLocation(locationTrackingCallback: LocationTrackingCallback?)`

  从融合位置提供程序客户端检索当前的设备位置，并将其上传到 Amazon Location 跟踪器。
+ **类**：`LocationTracker`

  `uploadLocationUpdates(locationTrackingCallback: LocationTrackingCallback?)`

  根据配置的位置筛选器进行筛选后，将设备位置上传到 Amazon Location Service。
+ **类**：`LocationTracker`

  `enableFilter(filter: LocationFilter)`

  启用特定位置筛选器。
+ **类**：`LocationTracker`

  `checkFilterIsExistsAndUpdateValue(filter: LocationFilter)`

  禁用特定位置筛选器。
+ **类**：`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()) `

  它使用用户定义的参数值初始化 `LocationTrackerConfig`。如果未提供参数值，会将其设置为默认值。
+ **类**：`LocationFilter`

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

  `LocationFilter` 是用户可以为其自定义筛选器实现实施的协议。您需要实现 `shouldUpload` 函数来比较以前和当前的位置，并返回是否应该上传当前位置。

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

以下代码示例显示了移动跟踪 SDK 功能。

此示例使用 `LocationTracker` 在后台开始和停止跟踪：

```
// 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()
```

# 将 MapLibre 工具和相关库与 Amazon Location 结合使用
<a name="dev-maplibre"></a>

[MapLibre](https://maplibre.org/) 主要是一个用于在 Web 或移动应用程序中显示地图的渲染引擎。但是，它还包括对插件的支持，并提供处理 Amazon Location 其他方面的功能。以下内容根据您要使用的区域或位置，描述了您可以使用的工具。

**注意**  
要使用 Amazon Location 的任何功能，请[为您要使用的语言安装 AWS SDK](dev-by-language.md)。
+ **地图**

  要在应用程序中显示地图，您需要一个地图渲染引擎，该引擎将使用 Amazon Location 提供的数据并绘制到屏幕上。地图渲染引擎还提供平移和缩放地图，或者向地图添加标记、图钉和其他注释的功能。

  Amazon Location Service 建议使用 [MapLibre](https://github.com/maplibre/maplibre-gl-js) 渲染引擎渲染地图。MapLibre GL JS 是一款用于在 JavaScript 中显示地图的引擎，而 MapLibre Native 则为 iOS 或 Android 提供地图。

  MapLibre 还具有用于扩展核心功能的插件生态系统。有关更多信息，请访问 [https://maplibre.org/maplibre-gl-js/docs/plugins/](https://maplibre.org/maplibre-gl-js/docs/plugins/)。
+ **位置搜索**

  [为了简化搜索用户界面的创建，您可以使用网页版 [MapLibre 地理编码器](https://github.com/maplibre/maplibre-gl-geocoder)（Android 应用程序可以使用 Android Places 插件）。](https://github.com/maplibre/maplibre-plugins-android/tree/master/plugin-places)

  使用 [Amazon Location for MapLibre 地理编码器库](https://github.com/aws-geospatial/amazon-location-for-maplibre-gl-geocoder?tab=readme-ov-file)可简化在 JavaScript 应用程序中将 Amazon Location 与 `amazon-location-for-maplibre-gl-geocoder` 结合使用的过程。

  有关更多信息，请参阅 [使用 Amazon 位置 MapLibre 地理编码器 GL 插件](dev-maplibre-geocoder.md)。
+ **路线**
+ **地理围栏和跟踪器**

  MapLibre 没有任何用于地理围栏和跟踪的特定渲染或工具，但您可以使用渲染功能和[插件](https://maplibre.org/maplibre-gl-js/docs/plugins/)在地图上显示地理围栏和被跟踪的设备。

  被跟踪的设备可以使用 [MQTT](tracking-using-mqtt.md) 或手动向 Amazon Location Service 发送更新。可以使用 [AWS Lambda](https://docs.aws.amazon.com/lambda/) 对地理围栏事件进行响应。

许多开源库可用于为 Amazon Location Service 提供其他功能，例如提供空间分析功能的 [Turf](https://github.com/Turfjs/turf)。

许多库都使用开放标准 [GeoJSON](https://geojson.org/) 格式的数据。Amazon Location Service 提供了一个库，可将响应转换为 GeoJSON，以便在 JavaScript 应用程序中使用。有关更多信息，请参阅 [SDKs 以及 Amazon Location Service 的框架](dev-sdks.md)。

# 按语言划分的 SDK
<a name="dev-by-language"></a>

**开发工具包版本**  
我们建议您使用项目中使用的最新版本的 AWS 开发工具包以及任何其他开发工具包，并使开发工具包保持最新。AWS 开发工具包为您提供最新的特性和功能以及安全更新。例如，要查找适用于 JavaScript 的 AWS 开发工具包的最新版本，请参阅适用于* JavaScript 的 AWS 开发工具包*文档中的[浏览器安装](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/index.html#In_the_Browser)主题。

下表按应用程序类型（Web、移动或后端应用程序）提供了有关语言和框架的 AWS SDK 和地图渲染框架版本的信息。

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

以下 AWS SDK 和地图渲染框架版本可用于 Web 前端应用程序开发。


| 语言/框架 | AWS SDK  | 地图渲染框架 | 
| --- | --- | --- | 
|  **完全支持**  | 
|  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)  | 
|  **部分支持**  | 
|  Flutter  |  [https://docs.amplify.aws/start/q/integration/flutter/](https://docs.amplify.aws/start/q/integration/flutter/) AWS 尚未完全支持 Flutter，但通过 Amplify 提供有限的支持。  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) MapLibre Flutter 库被视为实验性质。  | 
|  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/)  |  MapLibre 不支持 PHP。  | 

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

以下 AWS SDK 和地图渲染框架版本可用于移动前端应用程序开发。


| 语言/框架 | AWS SDK  | 地图渲染框架 | 
| --- | --- | --- | 
|  **完全支持**  | 
|  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/)  适用于 Android 的 Amazon Location Service 移动身份验证 SDK：[https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-android](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-android) 适用于 Android 的 Amazon Location Service 移动跟踪 SDK：[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) 需要自定义绑定，因为 MapLibre 是基于 Java 的。  | 
|  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/) 适用于 iOS 的 Amazon Location Service 移动身份验证 SDK：[https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios) 适用于 iOS 的 Amazon Location Service 移动跟踪 SDK：[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)  | 
|  **部分支持**  | 
|  Flutter  |  [https://docs.amplify.aws/start/q/integration/flutter/](https://docs.amplify.aws/start/q/integration/flutter/) AWS 尚未完全支持 Flutter，但通过 Amplify 提供有限的支持。  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) MapLibre Flutter 库被视为实验性质。  | 

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

以下 AWS SDK 可用于后端应用程序开发。此处未列出地图渲染框架，因为后端应用程序通常不需要地图渲染。


| 语言 | 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/) AWS SDK for Rust 为开发人员预览版。  | 

------

# 按语言划分的地图渲染 SDK
<a name="map-rendering-by-language"></a>

建议使用 [MapLibre](https://github.com/maplibre/maplibre-gl-js) 渲染引擎渲染 Amazon Location Service 地图。

MapLibre 是一款用于在 Web 或移动应用程序中显示地图的引擎。MapLibre 还具有插件模型，并支持某些语言和平台的用户界面进行搜索和路线规划。

要了解有关 MapLibre 及其提供的功能的更多信息，请参阅[将 MapLibre 工具和相关库与 Amazon Location 结合使用](dev-maplibre.md)和[如何使用动态地图](dynamic-maps-how-to.md)。

下表按应用程序类型（Web 或移动应用程序）提供了有关语言和框架的地图渲染 SDK 版本的信息。

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

以下地图渲染 SDK 可用于 Web 前端应用程序开发。


| 语言/框架 | 地图渲染框架 | 
| --- | --- | 
|  **完全支持**  | 
|  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)  | 
|  **部分支持**  | 
|  Flutter  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) MapLibre Flutter 库被视为实验性质。  | 
|  Node.js  |   Node.js 不支持 MapLibre。  | 
|  PHP  |   MapLibre 不支持 PHP。  | 

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

以下地图渲染 SDK 可用于移动前端应用程序开发。


| 语言/框架 | 地图渲染框架 | 
| --- | --- | 
|  **完全支持**  | 
|  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) 需要自定义绑定，因为 MapLibre 是基于 Java 的。  | 
|  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)  | 
|  **部分支持**  | 
|  Flutter  |  [https://github.com/maplibre/flutter-maplibre-gl](https://github.com/maplibre/flutter-maplibre-gl) MapLibre Flutter 库被视为实验性质。  | 

------

# 地址表单 SDK
<a name="address-form-sdk"></a>

地址表单 SDK 简化了智能地址输入表单的构建。当用户开始键入内容时，使用 SDK 构建的地址表单会提供相关的地址建议。当用户选择建议时，地址表单会自动填写城市、州和邮政编码等字段。这样可以最大限度地减少手动输入，从而减少错误并加快数据输入速度。用户还可以在地图上预览所选地址，并调整其位置图钉以指示特定的入口或上车地点，从而显著提高准确性。

![\[显示自动完成功能的地址表单 SDK 演示\]](http://docs.aws.amazon.com/zh_cn/location/latest/developerguide/images/address-form-demo.gif)


## 试试看
<a name="address-form-try-it"></a>

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

试试功能齐全[的地址表演示](https://aws-geospatial.github.io/address-form-sdk-js/)。

### 自己动手
<a name="address-form-builder"></a>

跳转[开始使用](#address-form-getting-started)到开始使用地址表单 SDK 实现地址表单，或者使用 Location Service 的 WYSIWYG [地址表单生成器向导尝试无代码方法，该向导](https://console.aws.amazon.com/location/solution-builder/home#/address-form)由此 SDK 提供支持，可在亚马逊定位服务控制台中访问，网址为。[https://console.aws.amazon.com/location/](https://console.aws.amazon.com/location/)此交互式向导允许您创建带有预测性建议、自动字段填充和灵活布局的自定义表单。开发人员可以下载 React JavaScript TypeScript、React 或独立版本 HTML/JavaScript 的 ready-to-use软件包，无需编写任何代码即可轻松集成。

## 主要功能
<a name="address-form-features"></a>

地址表 SDK 的主要功能包括：
+ 为地址提供内置的预输入建议 POIs，并加快数据输入速度。
+ 启用可配置的地点类型搜索（例如邮政编码、地点），以获得更精确的结果。
+ 提供自动浏览器位置检测，让用户快速集中在当前区域。
+ 显示内置的地图可视化效果以提高清晰度和背景信息。
+ 允许在不丢失系统提供的位置的情况下调整地图上的地址位置，从而确保准确性和可控性。
+ 包括无需编码的 WYSIWYG 生成器工具，可节省时间和精力。
+ 为预输入实现去抖和缓存， APIs 以优化性能并降低成本。
+ 支持自定义样式，以匹配应用程序的品牌和用户体验。

它使用以下 Amazon Location Service API 操作来提供地址信息来填写表格：

**[GetTile](https://docs.aws.amazon.com/location/latest/APIReference/API_geomaps_GetTile.html)**  
检索用于渲染交互式地图的地图块，以可视化地址的位置并调整地址的位置。

**[Autocomplete](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Autocomplete.html)**  
在用户键入时提供实时地址建议。

**[Suggest](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Suggest.html)**  
在用户键入时提供实时地址和 POI 建议。

**[ReverseGeocode](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_ReverseGeocode.html)**  
如果用户选择根据当前位置自动填写地址，则将用户的当前位置转换为最近的已知地址地址。

**[GetPlace](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_GetPlace.html)**  
从 “自动补全” 或 “建议” API 的结果中选择地址后，检索所选地址的详细地点信息。

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

该软件开发工具[包在 Apache-2.0 许可下是免费和开源](https://github.com/aws-geospatial/address-form-sdk-js)的。您只需为 API 的使用付费。请查阅 [Amazon Location Service 定价页面](https://aws.amazon.com/location/pricing/)。

## 开始使用
<a name="address-form-getting-started"></a>

地址表单 SDK 可以在 React 应用程序中使用，也可以在独立的 HTML 和 JavaScript 页面中使用。请按照以下说明开始操作。

### 先决条件
<a name="address-form-prerequisites"></a>

**注意**  
地址表单 SDK 需要具有所需权限的 API 密钥才能正常工作。使用 Amazon Location Service 控制台中的[地址表单 SDK 生成器向导](https://console.aws.amazon.com/location/solution-builder/home#/address-form)创建具有以下权限的 API 密钥，或者按照以下说明手动创建 API 密钥。

使用地址表单 SDK 需要在 API 密钥策略中允许执行以下操作：
+ `geo-maps:GetTile`-这在显示地图组件时是必需的。请参阅 [GetTile](https://docs.aws.amazon.com/location/latest/APIReference/API_geomaps_GetTile.html)API 参考文档。
+ `geo-places:Autocomplete`-使用该`Autocomplete`操作实现预输入功能时必须这样做。请参阅[自动补全](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Autocomplete.html) API 参考。
+ `geo-places:Suggest`-使用该`Suggest`操作实现预输入功能时必须这样做。请参阅[建议](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Suggest.html) API 参考。
+ `geo-places:ReverseGeocode`-当允许用户使用浏览器的地理定位 API 提供其当前位置时，这是必需的。请参阅 [ReverseGeocode](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_ReverseGeocode.html)API 参考文档。
+ `geo-places:GetPlace`-使用预输入功能时，这是必需的。请参阅 [GetPlace](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_GetPlace.html)API 参考文档。

按照[使用 API 密钥进行身份验证](https://docs.aws.amazon.com/location/latest/developerguide/using-apikeys.html)指南创建具有必要权限的 Amazon Location Service API 密钥。

具有所需权限的 [CreateKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_CreateKey.html)API 的密钥策略示例：

#### CreateKey 申请地址表权限
<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"
    ]
  }
}
```

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

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

在你的 HTML 代码中加入 JavaScript 以下 CSS 和 SDK 的内容

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

从 npm 安装软件开发工具包：`npm install @aws/address-form-sdk-js`

### 使用 SDK
<a name="address-form-use-sdk"></a>

将以下代码添加到你的 React 应用程序中。`AMAZON_LOCATION_API_KEY`使用您的 API 密钥`AMAZON_LOCATION_REGION`和创建 API 密钥的区域进行更新。提交表单时，`onSubmit`回调函数会提供一个`getData`异步函数。使用`intendedUse`值调用此函数以检索表单数据。

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

**注意**  
`"Storage"`如果您需要存储或缓存结果，请使用。这样可以确保遵守亚马逊定位服务（Amazon Location Service）的[预期使用要求](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>
  );
}
```

------

## 支持的国家/地区
<a name="address-form-supported-countries"></a>

地址表单 SDK 支持使用 Amazon Location Service 在全球范围内自动填写地址。以下国家/地区完全支持地址字段解析，即每个地址组成部分都填充到各自的字段中：
+ 澳大利亚（AU）
+ 加拿大 (CA)
+ 法国（FR）
+ 中国香港（HK）
+ 爱尔兰（IE）
+ 新西兰（NZ）
+ 菲律宾（PH）
+ 新加坡（SG）
+ 英国（GB）
+ 美国（US）

所有其他国家/地区均处于预览状态。预览国家/地区在`addressLineOne`字段中显示完整的地址，不使用特定国家/地区的格式。未来的版本将改善这种行为，您可以使用最新版本的 SDK 来访问这些改进。

## 支持的 AWS 区域
<a name="address-form-supported-aws-regions"></a>

地址表单软件开发工具包和地址表单生成器向导可在运营Amazon Location Service的所有 AWS 地区使用，使用其`Current`版本 APIs。查看 [Amazon Location 支持区域中支持的区域](https://docs.aws.amazon.com/location/latest/developerguide/location-regions.html)的完整列表。

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

请参阅[自述文件 API 参考](https://github.com/aws-geospatial/address-form-sdk-js#api-reference)。