

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 開始使用 Amazon Location Service
<a name="getting-started"></a>

本主題可協助您開始使用 Amazon Location Service。請依照下列步驟建立您的第一個應用程式，並了解如何根據常見使用案例選擇適當的 Amazon Location API。

1. **設定 AWS 您的帳戶和存取權。**

   如果您還沒有 帳戶，系統會提示您建立一個帳戶。使用 AWS 免費方案，您可以為 Amazon Location Service 獲得三個月的免費方案。

   如果您已有 帳戶，則需要提供 Amazon Location Service 的存取權。

   繼續[設定您的帳戶](set-up.md)主題。

1. **了解並設定身分驗證。**

   若要使用 Amazon Location，必須將構成 Amazon Location 的資源和 APIs 存取權授予使用者。API Key、Amazon Cognito 和 AWS Identity and Access Management (IAM) 是授予 資源和動作 (APIs三個選項。

   繼續[使用 Amazon Location Service 驗證](access.md)主題。

1. **建立您的第一個位置應用程式。**

   請參閱 [建立您的第一個 Amazon Location Maps and Places 應用程式](first-app.md) 以建置您的第一個「Hello World」應用程式。

1. **選擇正確的 API。**

   Amazon Location 跨 Places、Routes、Maps 和 Geofences 和 Tracker 提供一組豐富的 APIs，以解決各種商業使用案例。

   若要進一步了解如何選擇 Amazon Location API，請參閱 [選擇正確的 API](choose-an-api.md) 以取得詳細資訊。

# 設定您的帳戶
<a name="set-up"></a>

本節說明如何使用 Amazon Location Service。您必須擁有 ， AWS 帳戶 並為想要使用它的使用者設定 Amazon Location 的存取權。

## 我第一次使用 AWS
<a name="new-user"></a>

### 註冊 AWS 帳戶
<a name="sign-up-for-aws"></a>

如果您沒有 AWS 帳戶，請完成下列步驟來建立一個。

**註冊 AWS 帳戶**

1. 開啟 [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup)。

1. 請遵循線上指示進行。

   部分註冊程序需接收來電或簡訊，並在電話鍵盤輸入驗證碼。

   當您註冊 時 AWS 帳戶，*AWS 帳戶根使用者*會建立 。根使用者有權存取該帳戶中的所有 AWS 服務 和資源。作為安全最佳實務，請將管理存取權指派給使用者，並且僅使用根使用者來執行[需要根使用者存取權的任務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS 會在註冊程序完成後傳送確認電子郵件給您。您可以隨時登錄 [https://aws.amazon.com/](https://aws.amazon.com/) 並選擇**我的帳戶**，以檢視您目前的帳戶活動並管理帳戶。

### 建立具有管理存取權的使用者
<a name="create-an-admin"></a>

註冊 後 AWS 帳戶，請保護 AWS 帳戶根使用者、啟用 AWS IAM Identity Center和建立管理使用者，以免將根使用者用於日常任務。

**保護您的 AWS 帳戶根使用者**

1.  選擇**根使用者**並輸入 AWS 帳戶 您的電子郵件地址，以帳戶擁有者[AWS 管理主控台](https://console.aws.amazon.com/)身分登入 。在下一頁中，輸入您的密碼。

   如需使用根使用者登入的說明，請參閱 *AWS 登入 使用者指南*中的[以根使用者身分登入](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 若要在您的根使用者帳戶上啟用多重要素驗證 (MFA)。

   如需說明，請參閱《*IAM 使用者指南*》中的[為您的 AWS 帳戶 根使用者 （主控台） 啟用虛擬 MFA 裝置](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

**建立具有管理存取權的使用者**

1. 啟用 IAM Identity Center。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[啟用 AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html)。

1. 在 IAM Identity Center 中，將管理存取權授予使用者。

   如需使用 IAM Identity Center 目錄 做為身分來源的教學課程，請參閱*AWS IAM Identity Center 《 使用者指南*》中的[使用預設值設定使用者存取權 IAM Identity Center 目錄](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html)。

**以具有管理存取權的使用者身分登入**
+ 若要使用您的 IAM Identity Center 使用者簽署，請使用建立 IAM Identity Center 使用者時傳送至您電子郵件地址的簽署 URL。

  如需使用 IAM Identity Center 使用者登入的說明，請參閱*AWS 登入 《 使用者指南*》中的[登入 AWS 存取入口網站](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html)。

**指派存取權給其他使用者**

1. 在 IAM Identity Center 中，建立一個許可集來遵循套用最低權限的最佳實務。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[建立許可集](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)。

1. 將使用者指派至群組，然後對該群組指派單一登入存取權。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[新增群組](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)。

## 我已經有 AWS 帳戶
<a name="existing-user"></a>

**授予 Amazon Location Service 的存取權**

您的非管理員使用者預設沒有許可。您必須先連接具有特定許可的 IAM 政策，才能存取 Amazon Location。授予 資源存取權時，請務必遵循最低權限原則。

**注意**  
如需有關讓未驗證的使用者存取 Amazon Location Service 功能的資訊 （例如，在 Web 型應用程式中），請參閱 [使用 Amazon Location Service 驗證](access.md)。

下列範例政策提供使用者存取所有 Amazon Location 操作的許可。如需更多範例，請參閱[Amazon Location Service 的身分型政策範例](security-iam.md#security_iam_id-based-policy-examples)。

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "geo:*",
        "geo-maps:*",
        "geo-places:*",
        "geo-routes:*"
      ],
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}
```

若要提供存取權，請新增權限至您的使用者、群組或角色：
+ 中的使用者和群組 AWS IAM Identity Center：

  建立權限合集。請按照《*AWS IAM Identity Center 使用者指南*》中的[建立權限合集](https://docs.aws.amazon.com//singlesignon/latest/userguide/howtocreatepermissionset.html)說明進行操作。
+ 透過身分提供者在 IAM 中管理的使用者：

  建立聯合身分的角色。遵循《*IAM 使用者指南*》的[為第三方身分提供者 (聯合) 建立角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-idp.html)中的指示。
+ IAM 使用者：
  + 建立您的使用者可擔任的角色。請按照《*IAM 使用者指南*》的[為 IAM 使用者建立角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html)中的指示。
  + (不建議) 將政策直接附加至使用者，或將使用者新增至使用者群組。請遵循《*IAM 使用者指南*》的[新增許可到使用者 (主控台)](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) 中的指示。

建立使用 Amazon Location Service 的應用程式時，您可能需要一些使用者擁有未經驗證的存取權。如需這些使用案例，請參閱[使用 Amazon Cognito 啟用未經驗證的存取](authenticating-using-cognito.md)。

# 使用 Amazon Location Service 主控台進行身分驗證
<a name="set-up-auth"></a>

**注意**  
若要進一步了解身分驗證，請參閱 [使用 Amazon Location Service 驗證](access.md)。

若要使用 Amazon Location Service，必須將構成 Amazon Location 的資源和 APIs 存取權授予使用者。根據預設，Amazon Location APIs 需要身分驗證才能使用。您可以使用 Amazon Cognito 或 API 金鑰，為匿名使用者提供身分驗證和授權。

在[建立您的第一個 Amazon Location Maps and Places 應用程式](first-app.md)教學課程中，應用程式使用匿名，這表示您的使用者不需要登入。在教學課程中，您可以建立 API 金鑰，以便在範例應用程式中使用。

請依照下列程序建立您的第一個 API 金鑰。

1. 在 [https://console.aws.amazon.com/location](https://console.aws.amazon.com/location)中，從左側選單中選擇 **API 金鑰**。

1. 在 **API 金鑰**頁面上，選擇**建立 API 金鑰**。

1. 在**建立 API 金鑰**頁面上，填寫下列資訊：
   + **名稱** – API 金鑰的名稱，例如 `MyHelloWorldApp`。
   + **描述** – API 金鑰的選用描述。
   + **動作** – 指定您要使用此 API 金鑰授權的動作。您必須選取至少 **geo-maps：Get\$1** 和 **geo-places：Search\$1**。
   + **過期時間** – 選擇性地為您的 API 金鑰新增過期日期和時間。如需詳細資訊，請參閱[API 金鑰最佳實務](using-apikeys.md#api-keys-best-practices)。
   + **用戶端限制** – 選擇性地新增一或多個 Web 網域，或一或多個 Android 或 Apple 應用程式，您可以在其中使用 API 金鑰。例如，如果 API 金鑰是允許在網站 上執行的應用程式`example.com`，則可以將 `*.example.com/`做為允許的參考者。
   + **標籤** – 選擇性地將標籤新增至 API 金鑰。
**重要**  
如果不是兩者，我們建議您設定過期時間或推薦人來保護您的 API 金鑰用量。

1. 選擇**建立 API 金鑰**以建立 API 金鑰。

1. 在 API 金鑰的詳細資訊頁面上，您可以查看已建立之 API 金鑰的相關資訊。

   選擇**顯示 API 金鑰**並複製金鑰值，以在[建立您的第一個 Amazon Location Maps and Places 應用程式](first-app.md)教學課程中稍後使用。索引鍵值的格式為 `v1.public.a1b2c3d4...`。

# 選擇正確的 API
<a name="choose-an-api"></a>

本主題可協助您根據可能想要透過以位置為基礎的資料和服務解決的常見使用案例，選擇 Amazon Location Service API。

地圖  
地圖可為各種應用程式提供動態和靜態地圖類型的存取權。如需詳細資訊，請參閱 [Amazon Location Service Maps](maps.md)。  
+ **動態貼圖**：可即時自訂的互動式貼圖，可讓使用者平移、縮放和覆蓋資料。如需詳細資訊，請參閱 [動態映射](dynamic-maps.md)。
+ **靜態地圖**：地圖的靜態影像，顯示沒有互動元素的特定位置或路由，適用於互動受限的應用程式。如需詳細資訊，請參閱[靜態地圖](static-maps.md)。

路由  
Routes 提供計算位置之間最佳化路徑的功能。這些功能支援需要物流規劃、距離計算和路由最佳化的應用程式。使用者也可以將位置點貼齊道路，以提高準確性。如需詳細資訊，請參閱[Amazon Location Service Routes](routes.md)。  
+ **CalculateIsolines**：根據行程時間或距離產生等線，有助於定義服務區域或可到達性區域。如需詳細資訊，請參閱 [計算等線](calculate-isolines.md)。
+ **CalculateRouteMatrix**：提供多個原始伺服器和目的地之間的距離和行程時間的矩陣，支援物流和行程規劃。如需詳細資訊，請參閱 [計算路由矩陣](calculate-route-matrix.md)。
+ **CalculateRoutes**：計算point-to-point或多站導覽的最佳化路由，包括可自訂的路由偏好設定。如需詳細資訊，請參閱 [計算路由](calculate-routes.md)。
+ **OptimizeWaypoints**：最佳化最有效率行程路線的路線點順序，將距離或時間降至最低。如需詳細資訊，請參閱 [最佳化路徑點](actions-optimize-waypoints.md)。
+ **SnapToRoads**：將座標對齊最近的道路，透過將點貼齊已知道路來提高 GPS 準確性。如需詳細資訊，請參閱 [快照至道路](snap-to-roads.md)。

位置  
位置可讓應用程式搜尋、尋找和擷取有關興趣點、地址和特定位置的詳細資訊。這些功能透過提供內容和改善搜尋函數的使用者體驗來增強以位置為基礎的服務。如需詳細資訊，請參閱 [Amazon Location Service Places](places.md)。  
+ **Geocode**：將地址或位置名稱轉換為地理座標 （經度、緯度），支援需要address-to-location轉換以進行映射和空間分析的應用程式。如需詳細資訊，請參閱[Geocode](geocode.md)。
+ **反向地理編碼**：將地理座標轉換為最近的地址或位置名稱，提供位置的內容。如需詳細資訊，請參閱 [反向地理碼](reverse-geocode.md)。
+ **自動完成**：建議使用者輸入文字的潛在完成，提高搜尋輸入的效率。如需詳細資訊，請參閱 [自動完成](autocomplete.md)。
+ **GetPlace**：擷取指定位置的詳細資訊，包括地址、聯絡詳細資訊和營業時間等屬性。如需詳細資訊，請參閱 [GetPlace](get-place.md)。
+ **SearchNearby**：尋找指定地理點指定半徑內的位置，適用於「我附近」搜尋。如需詳細資訊，請參閱 [搜尋附近](search-nearby.md)。
+ **SearchText**：允許根據關鍵字或片語以文字為基礎的搜尋感興趣的位置或點，非常適合依名稱或描述尋找位置。如需詳細資訊，請參閱 [搜尋文字](search-text.md)。
+ **建議**：以使用者類型提供搜尋字詞建議，增強搜尋相關性和使用者體驗。如需詳細資訊，請參閱 [建議](suggest.md)。

地理圍欄  
Geofencing 允許應用程式定義地理邊界，並監控這些區域內的進入或退出事件。功能包括建立、更新和刪除地理圍欄，以及在追蹤的裝置跨越地理圍欄時設定位置型動作的通知或觸發條件。非常適合用於預先定義區域內的近接式通知、安全監控和資產追蹤。如需詳細資訊，請參閱 [Amazon Location Service 地理圍欄](geofences.md)。

追蹤器  
追蹤可即時監控裝置或資產位置一段時間。功能包括新增追蹤的裝置、更新其位置資料，以及擷取歷史位置資料。追蹤器有助於管理機群、監控人員，並透過提供up-to-date位置資料和移動模式來確保重要資產的安全性。如需詳細資訊，請參閱 [Amazon Location Service 追蹤器](trackers.md)。

# 建立您的第一個 Amazon Location Maps and Places 應用程式
<a name="first-app"></a>

在本節中，您將使用 Maps and Places 建立第一個應用程式。

**必要條件：**

如果您已在[使用 Amazon Location Service 主控台進行身分驗證](set-up-auth.md)步驟中建立 API 金鑰，讓我們開始。

如果您尚未建立 API 金鑰，請在繼續建置應用程式[使用 Amazon Location Service 主控台進行身分驗證](set-up-auth.md)之前遵循 。如果您有任何問題，請參閱 [使用 API 金鑰進行身分驗證](using-apikeys.md)和 [Amazon Location 支援的區域](location-regions.md) 以取得詳細資訊。

## Web
<a name="qs-web"></a>

以下是使用 MapLibre GL JS 建立 Amazon Location Service 地圖應用程式的step-by-step教學課程。本指南將逐步引導您設定地圖、新增樣式選項，以及啟用位置搜尋功能。

### 設定初始頁面
<a name="qs-initial-page"></a>

在本節中，我們將設定初始頁面和資料夾結構。

#### 新增必要的程式庫和樣式表
<a name="qs-initial-add-library"></a>

建立 `index.html` 檔案。若要轉譯映射，您需要 MapLibre GL JS 和 MapLibre GL Geocoder。您將新增 MapLibre 和 Geocoder 樣式表和 JavaScript 指令碼。

將下列程式碼複製並貼到您的 `index.html` 檔案中。

```
<!DOCTYPE html>
<html lang="en">
<head>

    <title>Amazon Location Service - Getting Started with First Map App</title>
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Interactive map application using Amazon Location Service">

    <!--Link to MapLibre CSS and JavaScript library for map rendering and visualization -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/dist/maplibre-gl.css" />
    <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/dist/maplibre-gl.js"></script>
    
    <!--Link to MapLibre Geocoder CSS and JavaScript library for place search and geocoding -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.css" />
    <script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.js"></script>
    
    <!--Link to amazon-location JavaScript librarie -->
    <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>
    <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1.2"></script>
    
    <!-- Link to the first Amazon Location Map App's CSS and JavaScript -->
    <script src="utils.js"></script>
    <link rel="stylesheet" href="style.css"/>
   

</head>
<body>
    <main> 
        
    </main>
    <script> 
        // Step 1: Setup API Key and AWS Region 
        // Step 2.1 Add maps to application
        // Step 2.2 initialize the map
        // Step 3: Add places features to application
        // Step 3.1: Get GeoPlaces instance. It will be used for addion search box and map click functionality
        // Step 3.2: Add search box to the map
        // Step 3.3.: Setup map click functionality
        // Add functions
    </script>
</body>
</html>
```

#### 建立映射容器
<a name="qs-create-map-container"></a>

 在 HTML 檔案的 `<body>`元素下，在您的 HTML 中建立`<div>`元素以保留映射。您可以在 CSS `<div>`中設定此樣式，以視需要為您的應用程式設定維度。您必須從 GitHub 儲存庫下載 CSS 檔案 `style.css`。這將協助您專注於商業邏輯。

 將 `style.css`和 `index.html` 檔案儲存在相同的資料夾中。

 從 [GitHub](https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/style.css) 下載 `style.css` 檔案。

```
<main role="main" aria-label="Map Container">
    <div id="map"></div>
</main>
```

#### 新增 API 金鑰和 AWS 區域詳細資訊
<a name="qs-create-add-key"></a>

將您在此檔案中建立的 API [使用 API 金鑰進行身分驗證](using-apikeys.md) 金鑰，以及建立金鑰 AWS 的區域。

```
<!DOCTYPE html>
<html lang="en">
.....
.....
<body>
    <main role="main" aria-label="Map Container">
        <div id="map"></div>
    </main>
    <script>
        // Step 1: Setup API Key and AWS Region 
        const API_KEY = "Your_API_Key";
        const AWS_REGION = "Region_where_you_created_API_Key";
        // Step 2: Add maps to application
            // Step 2.1 initialize the map
            // Step 2.2 Add navigation controls to the map
        // Step 3: Add places feature to application        
            // Step 3.1: Get GeoPlaces instance. It will be used for addion search box and map click functionality
            // Step 3.2: Add search box to the map
            // Step 3.3.: Setup map click functionality
    </script>
</body>
</html>
```

### 將地圖新增至您的應用程式
<a name="qs-add-map"></a>

在本節中，我們會將 Map 功能新增至應用程式。開始之前，您的檔案應位於此資料夾結構中。

 如果尚未這麼做，請從 [GitHub](https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/style.css) 下載`style.css`檔案。

```
|---FirstApp [Folder]
|-------------- index.html [File]
|-------------- style.css [File]
```

#### 建立 函數以初始化映射
<a name="qs-initialize-map-function"></a>

若要設定映射，請在行 `initializeMap(...)`後面建立下列函數 `//Add functions`。

選擇初始中心位置和縮放層級。在此範例中，我們將地圖中心設定為加拿大 Vancouver，縮放層級為 10。新增導覽控制項以輕鬆縮放。

```
/**
 * Initializes the map with the specified style and color scheme.
 */
function initializeMap(mapStyle = "Standard", colorScheme = "Dark") {
     const styleUrl = `https://maps.geo.${AWS_REGION}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${API_KEY}&color-scheme=${colorScheme}`;
     const map = new maplibregl.Map({
         container: 'map',                 // The ID of the map container
         style: styleUrl,                  // The style URL for the map
         center: [-123.116226, 49.246292], // Starting center coordinates
         zoom: 10,                         // Initial zoom level
         validateStyle: false              // Disable style validation
     });
     return map;                           // Return the initialized map
}
```

#### 初始化映射
<a name="qs-initialize-map"></a>

呼叫 `initializeMap(...)` 以初始化映射。或者，您可以在`initializeMap`函數之後，使用您偏好的樣式和顏色方案來初始化它。如需更多樣式選項，請參閱 [AWS 映射樣式和功能](map-styles.md)。

```
// Step 1: Setup API Key and AWS Region 
const API_KEY = "Your_API_Key";
const AWS_REGION = "Region_where_you_created_API_Key";

// Step 2.1 Add maps to application
// Step 2.2 initialize the map
const map = initializeMap("Standard","Light");

// Step 3: Add places features to application
```

在瀏覽器`index.html`中開啟 以查看正在執行的映射。

#### 新增導覽控制項
<a name="qs-add-navigation"></a>

或者，您可以將導覽控制項 （縮放和旋轉） 新增至地圖。這應該在呼叫 之後完成`initializeMap(...)`。

```
// Step 2.1 initialize the map
const map = initializeMap("Standard","Light");

// Step 2.2 Add navigation controls to the map
map.addControl(new maplibregl.NavigationControl());

// Step 3: Add places features to application
```

#### 檢閱地圖程式碼
<a name="qs-add-final"></a>

恭喜您！您的第一個應用程式已準備好使用映射。在瀏覽器`index.html`中開啟 。請確定 `style.css` 位於與 相同的資料夾中`index.html`。

您的最終 HTML 看起來應該如下所示：

```
<!DOCTYPE html>
<html lang="en">
<head>

   <title>Amazon Location Service - Getting Started with First Map App</title>
   <meta charset='utf-8'>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <meta name="description" content="Interactive map application using Amazon Location Service">

   <!-- Link to MapLibre CSS and JavaScript library for map rendering and visualization -->
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/dist/maplibre-gl.css" />
   <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/dist/maplibre-gl.js"></script>
   
   <!-- Link to MapLibre Geocoder CSS and JavaScript library for place search and geocoding -->
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.css" />
   <script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.js"></script>
   
   <!-- Link to amazon-location JavaScript library -->
   <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>
   <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1.2"></script>
   
   <!-- Link to the first Amazon Location Map App's CSS and JavaScript -->
   <script src="utils.js"></script>
   <link rel="stylesheet" href="style.css"/>
</head>

<body>
    <main role="main" aria-label="Map Container">
        <div id="map"></div>
    </main>
    <script>
        const API_KEY = "Your_API_Key";
        const AWS_REGION = "Region_where_you_created_API_Key";
        
        function initializeMap(mapStyle, colorScheme) {
            const styleUrl = `https://maps.geo.${AWS_REGION}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${API_KEY}&color-scheme=${colorScheme}`;
        
            const map = new maplibregl.Map({
                container: 'map',                 // ID of the HTML element for the map
                style: styleUrl,                  // URL for the map style
                center: [-123.116226, 49.246292], // Initial map center [longitude, latitude]
                zoom: 10                          // Initial zoom level
            });
            map.addControl(new maplibregl.NavigationControl());    
            return map;
        }
        
        const map = initializeMap("Standard", "Light");
        
    </script>
</body>
</html>
```

### 將位置新增至您的應用程式
<a name="qs-add-places"></a>

在本節中，我們將設定新增位置功能到應用程式。從 GitHub 下載 JavaScript 檔案[https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/utils.js](https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/utils.js)。

開始之前，您的檔案應位於此資料夾結構中：

```
|---FirstApp [Folder]
|-------------- index.html [File]
|-------------- style.css [File]
|-------------- utils.js [File]
```

#### 建立 函數以建立 GeoPlaces
<a name="qs-create-geoplaces"></a>

若要新增搜尋功能，請使用 `AuthHelper`和 初始化 `GeoPlaces`類別`AmazonLocationClient`。在 中的`</script>`標籤之前新增下列`getGeoPlaces(map)`函數`index.html`。

```
/**
 * Gets a GeoPlaces instance for Places operations.
 */
function getGeoPlaces(map) {
    const authHelper = amazonLocationClient.withAPIKey(API_KEY, AWS_REGION);                      // Authenticate using the API key and AWS region
    const locationClient = new amazonLocationClient.GeoPlacesClient(authHelper.getClientConfig()); // Create a GeoPlaces client
    const geoPlaces = new GeoPlaces(locationClient, map);                                          // Create GeoPlaces instance
    return geoPlaces;                                                                              // Return the GeoPlaces instance
}
```

#### 建立 函數以將搜尋方塊新增至應用程式
<a name="qs-add-searchbox"></a>

在 中的`</script>`標籤之前新增下列 `addSearchBox(map, geoPlaces)``renderPopup(feature)`、 和 `createPopup(feature)`函數`index.html`，以完成搜尋功能設定。

```
/**
 * Adds search box to the map.
 */
function addSearchBox(map, geoPlaces) {
    const searchBox = new MaplibreGeocoder(geoPlaces, {
        maplibregl,
        showResultsWhileTyping: true,                    // Show results while typing
        debounceSearch: 300,                             // Debounce search requests
        limit: 30,                                       // Limit number of results
        popuprender: renderPopup,                        // Function to render popup
        reverseGeocode: true,                            // Enable reverse geocoding
        zoom: 14,                                        // Zoom level on result selection
        placeholder: "Search text or nearby (lat,long)"  // Placeholder text for search box.
    });
    
    // Add the search box to the map
    map.addControl(searchBox, 'top-left'); 

    // Event listener for when a search result is selected
    searchBox.on('result', async (event) => {
        const { id, result_type } = event.result;                     // Get result ID and type
        if (result_type === "Place") {                                // Check if the result is a place
            const placeResults = await geoPlaces.searchByPlaceId(id); // Fetch details for the selected place
            if (placeResults.features.length) {
                createPopup(placeResults.features[0]).addTo(map);     // Create and add popup for the place
            }
        }
    });
}

/**
 * Renders the popup content for a given feature.
 */
function renderPopup(feature) {
    return `
        <div class="popup-content">
            <span class="${feature.place_type.toLowerCase()} badge">${feature.place_type}</span><br>
            ${feature.place_name}
        </div>`;
}

/**
 * Creates a popup for a given feature and sets its position.
 */
function createPopup(feature) {
    return new maplibregl.Popup({ offset: 30 })      // Create a new popup
        .setLngLat(feature.geometry.coordinates)     // Set the popup position
        .setHTML(renderPopup(feature));              // Set the popup content
}
```

#### 將搜尋方塊新增至應用程式
<a name="qs-add-searchbox-to-application"></a>

呼叫 `getGeoPlaces(map)` 3.1 節中定義的 來建立`GeoPlaces`物件，然後呼叫 `addSearchBox(map, geoPlaces)`將搜尋方塊新增至應用程式。

```
// Step 2: Add maps to application
// Step 2.1 initialize the map
const map = initializeMap("Standard","Light");
// Step 2.2 Add navigation controls to the map
map.addControl(new maplibregl.NavigationControl()); 

// Step 3: Add places feature to application        
// Step 3.1: Get GeoPlaces instance. It will be used for adding search box and map click functionality
const geoPlaces = getGeoPlaces(map);
// Step 3.2: Add search box to the map
addSearchBox(map, geoPlaces);
```

您的位置搜尋已準備好可供使用。在瀏覽器`index.html`中開啟 以查看其運作中的狀態。

#### 新增函數以在使用者按一下地圖時顯示快顯視窗
<a name="qs-add-map-click-feature"></a>

建立 函數`addMapClick(map, geoPlaces)`，以在使用者按一下地圖時顯示快顯視窗。在`</script>`標籤前面新增此函數。

```
/**
 * Sets up reverse geocoding on map click events.
 */
function addMapClick(map, geoPlaces) {
    map.on('click', async ({ lngLat }) => {                     // Listen for click events on the map
        const response = await geoPlaces.reverseGeocode({ query: [lngLat.lng, lngLat.lat], limit: 1, click: true }); // Perform reverse geocoding

        if (response.features.length) {                         // If there are results
            const clickMarker = new maplibregl.Marker({ color: "orange" }); // Create a marker
            const feature = response.features[0];               // Get the clicked feature
            const clickedPopup = createPopup(feature);          // Create popup for the clicked feature
            clickMarker.setLngLat(feature.geometry.coordinates) // Set marker position
                .setPopup(clickedPopup)                         // Attach popup to marker
                .addTo(map);                                    // Add marker to the map

            clickedPopup.on('close', () => clickMarker.remove()).addTo(map); // Remove marker when popup is closed
        }
    });
}
```

#### 呼叫 函數以新增對應點選功能
<a name="qs-call-map-click-feature"></a>

若要啟用地圖點選動作，請在包含 的行`addMapClick(map, geoPlaces)`後面呼叫 `addSearchBox(map, geoPlaces)`。

```
// Step 3: Add places feature to application        
// Step 3.1: Get GeoPlaces instance. It will be used for adding search box and map click functionality
const geoPlaces = getGeoPlaces(map);
// Step 3.2: Add search box to the map
addSearchBox(map, geoPlaces);
// Step 3.3: Setup map click functionality
addMapClick(map, geoPlaces);
```

#### 檢閱地圖和位置應用程式
<a name="qs-review-places"></a>

恭喜您！您的第一個應用程式已準備好使用 Maps and Places。在瀏覽器`index.html`中開啟 。確定 `style.css`和 `utils.js` 位於與 相同的資料夾中`index.html`。

您的最終 HTML 看起來應該如下所示：

```
<!DOCTYPE html>
<html lang="en">
<head>

   <title>Amazon Location Service - Getting Started with First Map App</title>
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Interactive map application using Amazon Location Service">

    <!--Link to MapLibre CSS and JavaScript library for map rendering and visualization -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/dist/maplibre-gl.css" />
    <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/dist/maplibre-gl.js"></script>
    
    <!--Link to MapLibre Geocoder CSS and JavaScript library for place search and geocoding -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.css" />
    <script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.js"></script>
    
    <!--Link to amazon-location JavaScript librarie -->
    <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>
    <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1.2"></script>
    
    <!-- Link to the first Amazon Location Map App's CSS and JavaScript -->
    <script src="utils.js"></script>
    <link rel="stylesheet" href="style.css"/>
   

</head>
<body>
    <main role="main" aria-label="Map Container">
        <div id="map"></div>
    </main>
    <script>
        // Step 1: Setup API Key and AWS Region
        const API_KEY = "Your_API_Key";
        const AWS_REGION = "Region_where_you_created_API_Key";
        
        
        // Step 2: Add maps to application
        // Step 2.1 initialize the map
        const map = initializeMap("Standard","Light");
        // Step 2.2 Add navigation controls to the map
        map.addControl(new maplibregl.NavigationControl()); 

        // Step 3: Add places feature to application        
        // Step 3.1: Get GeoPlaces instance. It will be used for addion search box and map click functionality
        const geoPlaces =  getGeoPlaces(map);
        // Step 3.2: Add search box to the map
        addSearchBox(map, geoPlaces);
        // Step 3.3.: Setup map click functionality
        addMapClick(map, geoPlaces); 
                
 

        /**
         * Functions to add maps and places feature.
         */
         
         /**
         * Initializes the map with the specified style and color scheme.
         */ 
        function initializeMap(mapStyle = "Standard", colorScheme = "Dark") {
            const styleUrl = `https://maps.geo.${AWS_REGION}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${API_KEY}&color-scheme=${colorScheme}`;
            const map = new maplibregl.Map({
                container: 'map',                   // The ID of the map container
                style: styleUrl,                    // The style URL for the map
                center: [-123.116226, 49.246292],   // Starting center coordinates
                zoom: 10,                           // Initial zoom level
                validateStyle: false                // Disable style validation
            });
            return map;                             // Return the initialized map
        }
        
        /**
         * Gets a GeoPlaces instance for Places operations.
         */
        function getGeoPlaces(map) {
            const authHelper =  amazonLocationClient.withAPIKey(API_KEY, AWS_REGION);                      // Authenticate using the API key and AWS region
            const locationClient = new amazonLocationClient.GeoPlacesClient(authHelper.getClientConfig()); // Create a GeoPlaces client
            const geoPlaces = new GeoPlaces(locationClient, map);                                          // Create GeoPlaces instance
                return geoPlaces;                                                                          // Return the GeoPlaces instance
        }
        
         /**
         * Adds search box to the map.
         */
        
        function addSearchBox(map, geoPlaces) {
            const searchBox = new MaplibreGeocoder(geoPlaces, {
                maplibregl,
                showResultsWhileTyping: true,                    // Show results while typing
                debounceSearch: 300,                             // Debounce search requests
                limit: 30,                                       // Limit number of results
                popuprender: renderPopup,                        // Function to render popup
                reverseGeocode: true,                            // Enable reverse geocoding
                zoom: 14,                                        // Zoom level on result selection
                placeholder: "Search text or nearby (lat,long)"  // Place holder text for search box.  
            });
            
            // Add the search box to the map
            map.addControl(searchBox, 'top-left'); 

            // Event listener for when a search result is selected
            searchBox.on('result', async (event) => {
                const { id, result_type } = event.result;                     // Get result ID and type
                if (result_type === "Place") {                                // Check if the result is a place
                    const placeResults = await geoPlaces.searchByPlaceId(id); // Fetch details for the selected place
                    if (placeResults.features.length) {
                        createPopup(placeResults.features[0]).addTo(map);     // Create and add popup for the place
                    }
                }
            });
        }

        /**
         * Renders the popup content for a given feature.
         */
        function renderPopup(feature) {
            return `
                <div class="popup-content">
                    <span class="${feature.place_type.toLowerCase()} badge">${feature.place_type}</span><br>
                    ${feature.place_name}
                </div>`;
        }

        /**
         * Creates a popup for a given feature and sets its position.
         */
        function createPopup(feature) {
            return new maplibregl.Popup({ offset: 30 })      // Create a new popup
                .setLngLat(feature.geometry.coordinates)     // Set the popup position
                .setHTML(renderPopup(feature));              // Set the popup content
        }
        
        /**
         * Sets up reverse geocoding on map click events.
         */
        function addMapClick(map, geoPlaces) {
            map.on('click', async ({ lngLat }) => {                     // Listen for click events on the map
                const response = await geoPlaces.reverseGeocode({ query: [lngLat.lng, lngLat.lat], limit: 1, click:true }); // Perform reverse geocoding

                if (response.features.length) {                         // If there are results
                    const clickMarker = new maplibregl.Marker({ color: "orange" }); // Create a marker
                    const feature = response.features[0];               // Get the clicked feature
                    const clickedPopup = createPopup(feature);          // Create popup for the clicked feature
                    clickMarker.setLngLat(feature.geometry.coordinates) // Set marker position
                        .setPopup(clickedPopup)                         // Attach popup to marker
                        .addTo(map);                                    // Add marker to the map

                    clickedPopup.on('close', () => clickMarker.remove()).addTo(map); // Remove marker when popup is closed
                }
            });
        }
        
    </script>
</body>
</html>
```

### 探索更多
<a name="qs-whats-next"></a>

您已完成快速入門教學課程，並應了解 Amazon Location Service 如何用於建置應用程式。若要進一步了解 Amazon Location，您可以查看下列資源：
+ **查詢建議詳細資訊** - 考慮將 `GeoPlaces` 類別或使用類似的方法來 `ReverseGeocode`，以取得 `Suggestion` API 傳回之結果的詳細資訊。
+ **選擇適合您業務需求的 API** - 若要判斷符合您需求的最佳 Amazon Location API，請查看此資源：[選擇正確的 API](choose-an-api.md)。
+ **請參閱 Amazon Location "how-to" 指南** - 請造訪 [Amazon Location Service 開發人員指南](https://docs.aws.amazon.com/location/)以取得教學課程和其他資源。
+ **文件和產品資訊** - 如需完整的文件，請參閱 [Amazon Location Service 開發人員指南](https://docs.aws.amazon.com/location/)。若要進一步了解產品，請前往 [Amazon Location Service 產品](https://aws.amazon.com/location)頁面。

# 建立您的第一個 Geofences 和追蹤器應用程式
<a name="first-geofence-app"></a>

在本節中，您將建立一個應用程式，示範使用 Amazon Location Geofences 和追蹤器的主要功能。應用程式示範追蹤器和地理ofence 如何使用 Lambda AWS IoT和 Amazon Location 功能的組合進行互動。選擇 iOS 或 Android 平台以開始使用。

開始建置應用程式之前，請遵循中的程序[使用 Amazon Location Service 主控台進行身分驗證](set-up-auth.md)授予適當的存取權。

**Topics**
+ [建立 iOS 應用程式](ios-geofence-app.md)
+ [建立 Android 應用程式](android-geofence-app.md)

# 建立 iOS 應用程式
<a name="ios-geofence-app"></a>

請依照這些程序，使用 Amazon Location Service 建置 iOS 應用程式。

從 [GitHub](https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications) 複製專案檔案。

## 為您的應用程式建立 Amazon Location 資源
<a name="qs-ios-tracking-resources"></a>

您可以在 AWS 帳戶準備就緒後產生 Amazon Location Service 資源。這些資源對於執行提供的程式碼片段至關重要。

**注意**  
如果您尚未建立 AWS 帳戶，請[建立 AWS 帳戶](https://portal.aws.amazon.com/billing/signup#/start/email)。

若要開始，您需要建立 Amazon Cognito 身分集區 ID，請使用下列程序：

1. 在 AWS 主控台中，導覽至 Amazon Cognito 服務，然後從左側功能表中選取**身分集**區，然後選取**建立身分集區**。

1. 確定已核取**訪客存取**，然後按**下一步**繼續。

1. 接著建立新的 IAM 角色或使用現有的 IAM 角色。

1. 輸入身分集區名稱，並確保身分集區可以存取您將在下一個程序中建立的映射和追蹤器的 Amazon Location `(geo)` 資源。

1. 

現在您需要在 Amazon Location AWS 主控台中建立地圖並建立樣式，請使用下列程序：

1. 導覽至 Amazon Location 主控台中的[映射區段](https://console.aws.amazon.com/location/maps/home)，然後選取**建立映射**以預覽可用的映射樣式。

1. 為新的映射資源命名****和**描述**。記錄您指派給映射資源的名稱，因為它稍後會在教學課程中使用。

1. 選擇映射樣式時，請考慮映射資料提供者。如需詳細資訊，請參閱 [AWS 服務條款](https://aws.amazon.com/service-terms)的第 82 節。

1.  接受 [Amazon Location 條款與條件](https://aws.amazon.com/service-terms/#:~:text=82.%20Amazon%20Location%20Service)，然後選取**建立映射**。建立地圖之後，您可以透過放大、縮小或平移任何方向來與地圖互動。

使用 Amazon Location 主控台建立追蹤器

1.  開啟 [Amazon Location Service 主控台](https://console.aws.amazon.com/location/)。

1.  在左側導覽窗格中，選擇**追蹤器**。

1.  選擇**建立追蹤器**。

1.  填寫所有必要欄位。

1.  在**位置篩選**下，選擇最符合您打算如何使用追蹤器資源的選項。如果您未設定位置篩選，則預設設定為 TimeBased。如需詳細資訊，請參閱本指南中的追蹤器，以及《Amazon Location Service Trackers API 參考》中的 PositionFiltering。

1.  選擇**建立追蹤器**以完成。

## 建立 Geofence 集合
<a name="qs-ios-tracking-geofence"></a>

建立地理圍欄集合時，您可以使用主控台、API 或 CLI。下列程序會逐步解說每個選項。

使用 Amazon Location 主控台建立地理圍欄集合：

1.  開啟位於 https：//https://console.aws.amazon.com/location/ 的 Amazon Location Service 主控台。

1.  在左側導覽窗格中，選擇 Geofence 集合。

1.  選擇建立地理圍欄集合。

1.  提供集合的名稱和描述。

1.  在以 CloudWatch 做為目標的 EventBridge 規則下，您可以建立選用的 EventBridge 規則，以開始對地理圍欄事件做出反應。這讓 Amazon Location 能夠將事件發佈到 Amazon CloudWatch Logs 中。

1.  選擇建立地理圍欄集合。

使用 Amazon Location APIs 建立地理圍欄集合：

從 Amazon Location Geofences APIs 使用 CreateGeofenceCollection 操作。下列範例使用 API 請求來建立名為 的地理圍欄集合`GOECOLLECTION_NAME`。

```
POST /geofencing/v0/collections
Content-type: application/json
    {
        "CollectionName": "GOECOLLECTION_NAME",
        "Description": "Geofence collection 1 for shopping center",
        "Tags": { 
            "Tag1" : "Value1"
                }
    }
```

使用 AWS CLI 命令建立地理圍欄集合：

使用 create-geofence-collection 命令。下列範例使用 AWS CLI 來建立名為 的地理圍欄集合`GOECOLLECTION_NAME`。

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

## 將追蹤器連結至地理圍欄集合
<a name="qs-ios-tracking-link-geofence"></a>

若要將追蹤器連結至地理圍欄集合，您可以使用主控台、API 或 CLI。下列程序會逐步解說每個選項。

使用 Amazon Location Service 主控台將追蹤器資源連結至地理圍欄集合：

1. 開啟 Amazon Location 主控台。

1. 在左側導覽窗格中，選擇**追蹤器**。

1. 在**裝置追蹤器**下，選取目標追蹤器的名稱連結。

1. 在**連結的地理圍欄集合**下，選擇**連結地理圍欄集合**。

1. 在**連結的地理圍欄集合視窗中**，從下拉式功能表中選取地理圍欄集合。

1. 選擇 **Link (連結)**。

1. 連結追蹤器資源後，會為其指派作用中狀態。

使用 Amazon Location APIs 將追蹤器資源連結至地理圍欄集合：

從 Amazon Location Trackers APIs 使用 ``AsssociateTrackerConsumer 操作。下列範例使用 API 請求，該請求使用其 Amazon Resource Name (ARN) 將 ExampleTracker 與地理圍欄集合建立關聯。

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

使用 AWS CLI 命令將追蹤器資源連結至地理圍欄集合：

使用 `associate-tracker-consumer ` 命令。下列範例使用 AWS CLI 來建立名為 的地理圍欄集合`GOECOLLECTION_NAME`。

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

## 搭配 MQTT 使用 AWS Lambda
<a name="qs-ios-tracking-lambda"></a>

建立 Lambda 函數。

若要在 AWS IoT Core 與 Amazon Location Service 之間建立連線，您需要 AWS Lambda 函數來處理由 EventBridge CloudWatch 事件轉送的訊息。此函數會擷取任何位置資料、將其格式化為 Amazon Location Service，並透過 Amazon Location Tracker API 提交資料。您可以透過 AWS Lambda 主控台建立此函數，也可以使用 AWS Command Line Interface (AWS CLI) 或 AWS Lambda APIs。若要建立使用主控台將位置更新發佈至 Amazon Location 的 Lambda 函數：

1.  在 https：//https://console.aws.amazon.com/lambda/ 開啟 AWS Lambda 主控台。

1. 從左側導覽中，選擇函數。

1. 選擇建立函數，並確定已選取從頭開始撰寫。

1. 填寫下列方塊：
   + 函數名稱
   + 針對**執行期**選項，選擇 Node.js 16.x。

1. 選擇建立函數。

1. 選擇程式碼索引標籤以開啟編輯器。

1. 使用下列項目覆寫 index.js 中的預留位置程式碼：

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

1. 選擇部署以儲存更新的函數。

1. 選擇 Configuration (組態) 索引標籤。

1. 在觸發條件區段中，按一下新增觸發條件。

1. 在來源欄位中選取 EventBridge (CloudWatch Events)。

1. 選取 `現有規則` 選項選項。

1. 輸入類似此 `AmazonLocationMonitor-GEOFENCECOLLECTION\$1NAME` 的規則名稱。

1. 按一下新增按鈕。

1. 這也會在許可索引標籤中連接 `Resource 型政策陳述式`

MQTT 測試用戶端

1. 開啟 https：//[https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格中，選擇 MQTT 測試用戶端。

1. 您將看到標題為 **MQTT 測試用戶端**的區段，您可以在其中設定 MQTT 連線。

1. 設定必要的設定後，按一下**連線**按鈕，使用提供的參數建立與 MQTT 代理程式的連線。

1. 請記下端點值。

連線後，您可以使用 MQTT 測試用戶端界面中提供的個別輸入欄位，訂閱 MQTT 主題或將訊息發佈至主題。接下來，您將連接 MQTT 政策：

1.  在左側選單的**管理**展開**安全性**選項下，按一下**政策**。

1. 按一下**建立政策**按鈕。

1. 輸入政策名稱。

1. 在**政策文件**上，選取 **JSON** 索引標籤。

1. 複製貼上以下顯示的政策，但請務必使用 `REGION`和 更新所有元素`ACCOUNT_ID`：

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

1. 選取要完成的**建立**按鈕。

## 設定範例應用程式程式碼
<a name="qs-ios-tracking-setup-sample"></a>

若要設定範例程式碼，您必須安裝下列工具：
+ Git
+ XCode 15.3 或更新版本
+ iOS 模擬器 16 或更新版本

使用此程序來設定範例應用程式程式碼：

1. 從此 URL 複製 git 儲存庫：https：//[https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications](https://github.com/aws-geospatial/amazon-location-samples-ios/tree/main/tracking-with-geofence-notifications)。

1. 開啟 `AWSLocationSampleApp.xcodeproj` 專案檔案。

1. 等待套件解析程序。

1. **選用**：在專案導覽功能表上，將 重新命名`ConfigTemplate.xcconfig`為 `Config.xcconfig`並填入下列值：

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

## 使用範例應用程式
<a name="qs-ios-tracking-usage"></a>

設定範例程式碼之後，您現在可以在 iOS 模擬器或實體裝置上執行應用程式。

1. 建置並執行應用程式。

1. 應用程式會要求您提供位置和通知許可。您需要允許它們。

1. 輕觸 `Cognito Configuration` 按鈕。

1. 如果您尚未在 `Config.xcconfig` 檔案中填入值，則需要將先前在組態畫面中建立的資源值填入 欄位。

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

1. 儲存組態

1. 您現在可以查看時間、距離和準確性的篩選條件選項。根據您的需求使用它們。

1. 前往應用程式中的 `Tracking` 索引標籤，您會看到地圖和 `Start Tracking` 按鈕。

1. 如果您已在模擬器上安裝應用程式，您可能想要模擬位置變更。這可以在功能 -> 位置選單選項中完成。例如，選取功能 -> 位置 -> 高速公路。

1. 輕觸 `Start Tracking` 按鈕。您應該會在地圖上看到追蹤點。

1. 應用程式也會追蹤背景中的位置。因此，當您在背景移動應用程式時，會要求您的許可，才能在背景模式中繼續追蹤。

1. 您可以點選 `Stop Tracking` 按鈕來停止追蹤。

# 建立 Android 應用程式
<a name="android-geofence-app"></a>

請依照這些程序，使用 Amazon Location Service 建置 iOS 應用程式。

從 [GitHub](https://github.com/aws-geospatial/amazon-location-samples-android/tree/main/tracking-with-geofence-notifications) 複製專案檔案。

## 為您的應用程式建立 Amazon Location 資源
<a name="qs-android-tracking-resources"></a>

您可以在 AWS 帳戶準備就緒後產生 Amazon Location Service 資源。這些資源對於執行提供的程式碼片段至關重要。

**注意**  
如果您尚未建立 AWS 帳戶，請[建立 AWS 帳戶](https://portal.aws.amazon.com/billing/signup#/start/email)。

若要開始，您需要建立 Amazon Cognito 身分集區 ID，請使用下列程序：

1. 在 AWS 主控台中，導覽至 Amazon Cognito 服務，然後從左側功能表中選取**身分集**區，然後選取**建立身分集區**。

1. 確定已核取**訪客存取**，然後按**下一步**繼續。

1. 接著建立新的 IAM 角色或使用現有的 IAM 角色。

1. 輸入身分集區名稱，並確保身分集區可以存取您將在下一個程序中建立的映射和追蹤器的 Amazon Location `(geo)`資源。

1. 

現在您需要在 Amazon Location AWS 主控台中建立地圖並建立樣式，請使用下列程序：

1. 導覽至 Amazon Location 主控台中的[映射區段](https://console.aws.amazon.com/location/maps/home)，然後選取**建立映射**以預覽可用的映射樣式。

1. 為新的映射資源命名****和**描述**。記錄您指派給映射資源的名稱，因為它稍後會在教學課程中使用。

1. 選擇映射樣式時，請考慮映射資料提供者。如需詳細資訊，請參閱 [AWS 服務條款](https://aws.amazon.com/service-terms)的第 82 節。

1. 接受 [Amazon Location 條款與條件](https://aws.amazon.com/service-terms/#:~:text=82.%20Amazon%20Location%20Service)，然後選取**建立映射**。建立地圖之後，您可以透過放大、縮小或平移任何方向來與地圖互動。

使用 Amazon Location 主控台建立追蹤器

1.  開啟 [Amazon Location Service 主控台](https://console.aws.amazon.com/location/)。

1. 在左側導覽窗格中，選擇**追蹤器**。

1. 選擇**建立追蹤器**。

1. 填寫所有必要欄位。

1. 在**位置篩選**下，選擇最符合您打算如何使用追蹤器資源的選項。如果您未設定位置篩選，則預設設定為 TimeBased。如需詳細資訊，請參閱本指南中的追蹤器，以及《Amazon Location Service Trackers API 參考》中的 PositionFiltering。

1. 選擇**建立追蹤器**以完成。

## 建立 Geofence 集合
<a name="qs-android-tracking-geofence"></a>

建立地理圍欄集合時，您可以使用主控台、API 或 CLI。下列程序會逐步解說每個選項。

使用 Amazon Location 主控台建立地理圍欄集合：

1. 開啟位於 https：//https://console.aws.amazon.com/location/ 的 Amazon Location Service 主控台。

1. 在左側導覽窗格中，選擇 Geofence 集合。

1. 選擇建立地理圍欄集合。

1. 提供集合的名稱和描述。

1. 在以 CloudWatch 做為目標的 EventBridge 規則下，您可以建立選用的 EventBridge 規則，以開始對地理圍欄事件做出反應。這讓 Amazon Location 能夠將事件發佈到 Amazon CloudWatch Logs 中。

1. 選擇建立地理圍欄集合。

使用 Amazon Location APIs 建立地理圍欄集合：

從 Amazon Location Geofences APIs 使用 CreateGeofenceCollection 操作。下列範例使用 API 請求來建立名為 的地理圍欄集合`GOECOLLECTION_NAME`。

```
POST /geofencing/v0/collections
Content-type: application/json
    {
    "CollectionName": "GOECOLLECTION_NAME",
    "Description": "Geofence collection 1 for shopping center",
    "Tags": { 
        "Tag1" : "Value1"
            }
    }
```

使用 AWS CLI 命令建立地理圍欄集合：

使用 create-geofence-collection 命令。下列範例使用 AWS CLI 來建立名為 的地理圍欄集合`GOECOLLECTION_NAME`。

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

## 將追蹤器連結至地理圍欄集合
<a name="qs-android-tracking-link-geofence"></a>

若要將追蹤器連結至地理圍欄集合，您可以使用主控台、API 或 CLI。下列程序會逐步解說每個選項。

使用 Amazon Location Service 主控台將追蹤器資源連結至地理圍欄集合：

1. 開啟 Amazon Location 主控台。

1. 在左側導覽窗格中，選擇**追蹤器**。

1. 在**裝置追蹤器**下，選取目標追蹤器的名稱連結。

1. 在**連結的地理圍欄集合**下，選擇**連結地理圍欄集合**。

1. 在**連結的地理圍欄集合視窗中**，從下拉式功能表中選取地理圍欄集合。

1. 選擇 **Link (連結)**。

1. 連結追蹤器資源後，會為其指派作用中狀態。

使用 Amazon Location APIs 將追蹤器資源連結至地理圍欄集合：

從 Amazon Location Trackers APIs 使用 ``AsssociateTrackerConsumer 操作。下列範例使用 API 請求，該請求使用其 Amazon Resource Name (ARN) 將 ExampleTracker 與地理圍欄集合建立關聯。

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

使用 AWS CLI 命令將追蹤器資源連結至地理圍欄集合：

使用 `associate-tracker-consumer ` 命令。下列範例使用 AWS CLI 來建立名為 的地理圍欄集合`GOECOLLECTION_NAME`。

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

## 搭配 MQTT 使用 AWS Lambda
<a name="qs-android-tracking-lambda"></a>

建立 Lambda 函數。

若要在 AWS IoT Core 與 Amazon Location Service 之間建立連線，您需要 AWS Lambda 函數來處理由 EventBridge CloudWatch 事件轉送的訊息。此函數會擷取任何位置資料、將其格式化為 Amazon Location Service，並透過 Amazon Location Tracker API 提交資料。您可以透過 AWS Lambda 主控台建立此函數，也可以使用 AWS Command Line Interface (AWS CLI) 或 AWS Lambda APIs。若要建立使用主控台將位置更新發佈至 Amazon Location 的 Lambda 函數：

1.  在 https：//https://console.aws.amazon.com/lambda/ 開啟 AWS Lambda 主控台。

1. 從左側導覽中，選擇函數。

1. 選擇建立函數，並確定已選取從頭開始撰寫。

1. 填寫下列方塊：
   + 函數名稱
   + 針對**執行期**選項，選擇 Node.js 16.x。

1. 選擇建立函數。

1. 選擇程式碼索引標籤以開啟編輯器。

1. 使用下列項目覆寫 index.js 中的預留位置程式碼：

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

1. 選擇部署以儲存更新的函數。

1. 選擇 Configuration (組態) 索引標籤。

1. 在觸發條件區段中，按一下新增觸發條件。

1. 在來源欄位中選取 EventBridge (CloudWatch Events)。

1. 選取 `現有規則` 選項選項。

1. 輸入類似此 `AmazonLocationMonitor-GEOFENCECOLLECTION\$1NAME` 的規則名稱。

1. 按一下新增按鈕。

1. 這也會在許可索引標籤中連接 `Resource 型政策陳述式`

MQTT 測試用戶端

1. 開啟 https：//[https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格中，選擇 MQTT 測試用戶端。

1. 您將看到標題為 **MQTT 測試用戶端**的區段，您可以在其中設定 MQTT 連線。

1. 設定必要的設定後，按一下**連線**按鈕，使用提供的參數建立與 MQTT 代理程式的連線。

1. 記下端點值。

連線後，您可以使用 MQTT 測試用戶端界面中提供的個別輸入欄位，訂閱 MQTT 主題或將訊息發佈至主題。接下來，您將連接 MQTT 政策：

1.  在左側選單的**管理**展開**安全性**選項下，按一下**政策**。

1. 按一下**建立政策**按鈕。

1. 輸入政策名稱。

1. 在**政策文件**上，選取 **JSON** 索引標籤。

1. 複製貼上以下顯示的政策，但請務必使用 `REGION`和 更新所有元素`ACCOUNT_ID`：

   ```
   {
    "Version": "2012-10-17",		 	 	 
    "Statement": [
                   {
                     "Action": [
                       "iot:Connect",
                       "iot:Publish",
                       "iot:Subscribe",
                       "iot:Receive"
                        ],
                     "Resource": [
                       "arn:aws:iot:REGION:ACCOUNT_ID:client/${cognito-identity.amazonaws.com:sub}",
                       "arn:aws:iot:REGION:ACCOUNT_ID:topic/${cognito-identity.amazonaws.com:sub}",
                       "arn:aws:iot:REGION:ACCOUNT_ID:topicfilter/${cognito-identity.amazonaws.com:sub}/",
                       "arn:aws:iot:REGION:ACCOUNT_ID:topic/${cognito-identity.amazonaws.com:sub}/tracker"
                       ],
                     "Effect": "Allow"
                   }
                 ]
   }
   ```
**注意**  
記錄要用於下一個程序的政策名稱和主題名稱。

1. 選取要完成的**建立**按鈕。

完成先前的程序後，您現在將更新訪客角色的許可，如下所示：

1. 導覽至 Amazon Cognito 並開啟您的身分集區。然後，繼續存取使用者，然後選取訪客角色。

1. 按一下許可政策以啟用編輯。

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

1. 隨著上述政策的變更，現在已針對應用程式適當設定所有必要 AWS 的資源。

## 設定範例應用程式程式碼
<a name="qs-android-tracking-sample-app-code"></a>



1. 開啟 Android Studio，然後選取**新增**，然後從**版本控制投影**。

1. 導覽至 Android Studio 左上角**的檔案**選單。

1. 從下拉式選單中選取「新增」。

1. 選擇「從版本控制專案」。

1. 輸入儲存庫 URL 在出現的對話方塊中，尋找標記為「URL」的欄位。

1. 將範例應用程式的下列 URL 複製並貼到此欄位：[https://github.com/aws-geospatial/amazon-location-samples-android.git](https://github.com/aws-geospatial/amazon-location-samples-android.git)

1. 決定您要複製儲存庫的目錄。使用預設目錄或選擇自訂位置。

1. 設定儲存庫 URL 和目錄偏好設定後，按一下「複製」按鈕。Android Studio 將繼續將儲存庫複製到您指定的位置。

1. 您現在已將應用程式複製到您的機器，並可以開始使用它。

## 使用範例應用程式
<a name="qs-android-tracking-use"></a>

若要使用範例，請遵循下列程序：
+ **建立 `custom.properties`**：

  若要設定 `custom.properties` 檔案，請依照下列步驟進行：

  1. 開啟您偏好的文字編輯器或 IDE。

  1. 建立新檔案。

  1. 儲存檔案，並將其命名為 `custom.properties`。

  1. `custom.properties` 使用以下程式碼範例更新 ，並將 `MQTT_END_POINT`、`GEOFENCE_COLLECTION_NAME`、 `POLICY_NAME`和 取代`TOPIC_TRACKER`為實際值：

     ```
     MQTT_END_POINT=xxxxxxxxxxxxx-xxx.xxx.us-east-1.amazonaws.com
     POLICY_NAME=xxxxxxxxx
     GEOFENCE_COLLECTION_NAME=xxxxxxxxxxxxxxxxx
     TOPIC_TRACKER=xxxxxxxxxx
     ```

  1. 清理和重建專案。之後，您可以執行專案。
+ **登入**：

  若要登入應用程式，請遵循下列步驟：

  1. 按下**登入**按鈕。

  1. 提供**身分集區 ID**、**追蹤器名稱**和**映射名稱**。

  1. 再次按下**登入**以完成。
+ **管理篩選條件**：

  開啟組態畫面，並執行下列動作：

  1. 使用切換 UI 開啟/關閉篩選條件。

  1. 視需要更新時間和距離篩選條件。
+ **追蹤操作：**

  開啟追蹤畫面並執行下列動作：
  + 您可以按下個別按鈕，在前景、背景或省電模式下開始和停止追蹤。