建立網路應用程式 - Amazon Location Service

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

建立網路應用程式

在本節中,您將創建一個靜態網頁,其中包含地圖和在某個位置進行搜索的功能。首先,您將創建您的 Amazon 位置資源,並為您的應用程序創建一個 API 密鑰。

為您的應用程式建立 Amazon 位置資源

如果您還沒有這些資源,則必須建立應用程式將使用的 Amazon 位置資源。在這裡,您可以創建一個地圖資源以在應用程序中顯示地圖,並創建地圖索引以在地圖上搜索位置。

將位置資源新增至您的應用程式
  1. 選擇您要使用的地圖樣式。

    1. 在 Amazon 位置主控台的「地」頁面上,選擇「建立地圖」以預覽地圖樣式。

    2. 為新地圖資源新增「名稱」和「描述」。記下您用於地圖資源的名稱。稍後在自學課程中建立腳本檔案時,您將需要它。

    3. 選擇地圖。

      注意

      選擇地圖型式也會選擇您將使用的地圖資料提供者。如果您的應用程式正在追蹤或路由您在業務中使用的資產,例如送貨車輛或員工,您只能使用 HERE 作為您的地理位置供應商。如需詳細資訊,請參閱AWS服務條款第 82 節。

    4. 同意 Amazon 位置條款與條件,然後選擇「建立地圖」。您可以與選擇的地圖互動:放大、縮小或向任何方向平移。

    5. 記下為您的新地圖資源顯示的 Amazon 資源名稱(ARN)。您將在本教程稍後使用它來創建正確的身份驗證。

  2. 選擇您要使用的位置索引。

    1. 在「放置索引」頁面上的 Amazon 位置主控台中,選擇「建立位置索引」。

    2. 新增位置索引資源的「名稱」和「說明」。記下您用於放置索引資源的名稱。稍後在自學課程中建立腳本檔案時,您將需要它。

    3. 選擇資料提供者。

      注意

      在大多數情況下,請選擇與您已選擇的地圖提供者相符的資料提供者。這有助於確保搜索將匹配地圖。

      如果您的應用程式正在追蹤或路由您在業務中使用的資產,例如送貨車輛或員工,您只能使用 HERE 作為您的地理位置供應商。如需詳細資訊,請參閱AWS服務條款第 82 節。

    4. 選擇數據存儲選項。在本自學課程中,不會儲存結果,因此您可以選擇「否,僅限單次使用」。

    5. 同意 Amazon 地點條款與條件,然後選擇建立地點索引

    6. 記下針對新位置索引資源顯示的 ARN。您將在本教程的下一部分中使用它來創建正確的身份驗證。

為您的應用程式設定驗證

您在本教程中創建的應用程序具有匿名用法,這意味著您的用戶不需AWS要登錄即可使用該應用程序。但是,根據預設,Amazon 定 Location Service API 需要身份驗證才能使用。您可以使用 Amazon Cognito 或 API 金鑰為匿名使用者提供身份驗證和授權。在本教學課程中,您將建立用於範例應用程式的 API 金鑰。

注意

如需將 API 金鑰或 Amazon Cognito 與 Amazon 定 Location Service 搭配使用的詳細資訊,請參閱授予對 Amazon 定 Location Service 的訪問

若要為您的應用程式設定驗證
  1. 轉到 Amazon 位置控制台,然後從左側菜單中選擇 API 密鑰

  2. 選擇建立 API 金鑰

    重要

    您建立的 API 金鑰必須AWS 帳戶與您在上一節建立的 Amazon 定 Location Service 資源所在的AWS區域相同。

  3. 其中一個「建立 API 金鑰」頁面,填寫下列資訊。

    • 名稱 — API 金鑰的名稱,例如MyWebAppKey

    • 資源 — 選擇您在上一節中建立的 Amazon 位置圖和放置索引資源。您可以選擇 [新增資源] 來新增多個資源。這將允許 API 密鑰與這些資源一起使用。

    • 動作 — 指定您要使用此 API 金鑰授權的動作。您必須至少選取 geo: GetMap *geo:,這SearchPlaceIndexfForPosition樣教學課程才能如預期般運作。

    • 您可以選擇性地在 API 金鑰中新增說明到期時間標籤。您還可以添加引用者(例如*.example.com),將密鑰限制為僅從特定域中使用。這意味著該教程將僅適用於該域。

      注意

      建議您通過設置到期時間或引用者(如果不是兩者)來保護您的 API 密鑰使用情況。

  4. 選擇「建立 API 金鑰」以建立 API 金鑰。

  5. 選擇 [顯示 API 金鑰],然後複製金鑰值以供稍後在教學課程中使用。它將以形式出現v1.public.a1b2c3d4...

    重要

    在本教程稍後為您的應用程序編寫代碼時,您將需要此密鑰。

為您的應用程式建立 HTML

在本教程中,您將創建一個嵌入地圖的靜態 HTML 頁面,並允許用戶查找地圖上的某個位置。該應用程序將由三個文件組成:網頁的 HTML 文件和 CSS 文件,以及一個 JavaScript (.js)文件,用於創建地圖並響應用戶的交互和地圖事件的代碼。

首先,讓我們創建將用於應用程序的 HTML 和 CSS 框架。這將是一個簡單的頁面,其中包含用於保存地圖容器的<pre>元素以及顯示查詢的 JSON 響應的元素。<div>

建立快速入門應用程式的 HTML
  1. 建立稱為 quickstart.html 的新檔案。

  2. 在您選擇的文字編輯器或環境中編輯檔案。將下面的 HTML 添加到文件中。

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Quick start tutorial</title> <!-- Styles --> <link href="main.css" rel="stylesheet" /> </head> <body> <header> <h1>Quick start tutorial</h1> </header> <main> <div id="map"></div> <aside> <h2>JSON Response</h2> <pre id="response"></pre> </aside> </main> <footer>This is a simple Amazon Location Service app. Pan and zoom. Click to see details about entities close to a point.</footer> </body> </html>

    此 HTML 具有指向您將在下一個步驟中建立的 CSS 檔案的指標、應用程式的某些預留位置元素,以及一些說明性文字。

    您將在本教學課程稍後使用兩個預留位置元素。第一個是<div id="map>元素,這將持有地圖控件。第二個是<pre id="response">元素,這將顯示在地圖上搜索的結果。

  3. 儲存您的檔案。

現在添加網頁的 CSS。這將設置應用程序的文本和佔位符元素的樣式。

建立快速入門應用程式的 CSS
  1. 在與先前程序中建立的 quickstart.html 檔案相同的資料夾中建立名main.css為的新檔案。

  2. 在您要使用的任何編輯器中編輯檔案。將下列文字新增至檔案。

    * { box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; } body { margin: 0; } header { background: #000000; padding: 0.5rem; } h1 { margin: 0; text-align: center; font-size: 1.5rem; color: #ffffff; } main { display: flex; min-height: calc(100vh - 94px); } #map { flex: 1; } aside { overflow-y: auto; flex: 0 0 30%; max-height: calc(100vh - 94px); box-shadow: 0 1px 1px 0 #001c244d, 1px 1px 1px 0 #001c2426, -1px 1px 1px 0 #001c2426; background: #f9f9f9; padding: 1rem; } h2 { margin: 0; } pre { white-space: pre-wrap; font-family: monospace; color: #16191f; } footer { background: #000000; padding: 1rem; color: #ffffff; }

    這將地圖設置為填充其他任何東西未使用的空間,將我們的響應區域設置為佔用應用程序寬度的 30%,並為標題和說明性文本設置顏色和樣式。

  3. 儲存檔案。

  4. 現在,您可以在瀏覽器中查看quickstart.html文件以查看應用程序的佈局。

接下來,您將地圖控制項新增至應用程式。

將交互式地圖添加到您的應用程序

現在您有架構和 div 預留位置,您可以將地圖控制項新增至應用程式。本教程使用 MapLibre GL JS 作為地圖控制項,從 Amazon 定 Location Service 獲取數據。您也可以使用JavaScript 驗證助手來協助使用您的 API 金鑰簽署對 Amazon 位置 API 的呼叫。

若要將互動式地圖加入至您的應用程式
  1. 開啟您在上一節中建立的quickstart.html檔案。

  2. 將參考新增至所需程式庫,以及您要建立的指令碼檔案。您需要進行的變更顯示在中green

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Quick start tutorial</title> <!-- Styles --> <link href="https://unpkg.com/maplibre-gl@3.x/dist/maplibre-gl.css" rel="stylesheet" /> <link href="main.css" rel="stylesheet" /> </head> <body> ... <footer>This is a simple Amazon Location Service app. Pan and zoom. Click to see details about entities close to a point.</footer> <!-- JavaScript dependencies --> <script src="https://unpkg.com/maplibre-gl@3.x/dist/maplibre-gl.js"></script> <script src="https://unpkg.com/@aws/amazon-location-client@1.x/dist/amazonLocationClient.js"></script> <script src="https://unpkg.com/@aws/amazon-location-utilities-auth-helper@1.x/dist/amazonLocationAuthHelper.js"></script> <!-- JavaScript for the app --> <script src="main.js"></script> </body> </html>

    這將以下依賴項添加到您的應用程序中:

    • MapLibre GL JS. 此物件庫和樣式表包括顯示地圖框並包含互動性 (例如平移和縮放) 的地圖控制項。該控制還允許擴展,例如在地圖上繪製自己的圖徵。

    • Amazon 位置客戶端。這為取得地圖資料以及在地圖上搜尋地點所需的 Amazon 位置功能提供界面。Amazon 位置客戶端是以 JavaScript v3 的 AWS SDK 為基礎。

    • Amazon 位置身份驗證助手 這為使用 API 金鑰或 Amazon Cognito 驗證亞馬遜定 Location Service 提供了實用的功能。

    此步驟也會新增參照main.js,您將在下一步建立該參照。

  3. 儲存 quickstart.html 檔案。

  4. 在與 HTML 和 CSS 檔案相同的資料夾main.js中建立名為的新檔案,然後開啟檔案進行編輯。

  5. 將以下腳本添加到您的文件中。紅色的文字應替換為您先前建立的 API 金鑰值、對映資源名稱和地點資源名稱,以及您所在地區的地區識別碼 (例如us-east-1)。

    // Amazon Location Service resource names: const mapName = "explore.map"; const placesName = "explore.place"; const region = "your_region"; const apiKey = "v1.public.a1b2c3d4... // Initialize a map async function initializeMap() { const mlglMap = new maplibregl.Map({ container: "map", // HTML element ID of map element center: [-77.03674, 38.891602], // Initial map centerpoint zoom: 16, // Initial map zoom style: 'https://maps.geo.${region}.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor?key=${apiKey}', // Defines the appearance of the map and authenticates using an API key }); // Add navigation control to the top left of the map mlglMap.addControl(new maplibregl.NavigationControl(), "top-left"); return mlglMap; } async function main() { // Initialize map and Amazon Location SDK client: const map = await initializeMap(); } main();

    此程式碼會設定 Amazon 位置資源,然後設定並初始化 MapLibre GL JS 地圖控制項,並將其放置在具有 id 的項<div>目中。map

    initializeMap()功能是重要的是要理解。它創建一個新的 MapLibre 地圖控制項(在mlglMap本地調用,但map在代碼的其餘部分調用),用於在應用程序中渲染地圖。

    // Initialize the map const mlglMap = new maplibregl.Map({ container: "map", // HTML element ID of map element center: [-77.03674, 38.891602], // Initial map centerpoint zoom: 16, // Initial map zoom style: 'https://maps.geo.${region}.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor?key=${apiKey}`, // Defines the appearance of the map and authenticates using an API key });

    當您建立新的 MapLibre 地圖控制項時,您傳遞的參數指示地圖控制項的初始狀態。在這裡,我們設置以下參數。

    • HTML 容器,它使用在我們的 HTML 地圖 div 元素。

    • 地圖的初始中心點到華盛頓特區的一個點。

    • 縮放層級為 16 (縮放至鄰近或圖塊層級)。

    • 用於地圖的樣式,它提供了 MapLibre 一個 URL,用於獲取地圖框和其他信息來渲染地圖。請注意,此 URL 包含用於驗證的 API 金鑰。

  6. 儲存 JavaScript 檔案,然後使用瀏覽器開啟檔案。現在,您的頁面上有一個地圖,您可以在其中使用平移和縮放動作。

    注意

    您可以使用此應用程序來查看 MapLibre 地圖控件的行為。您可以在使用拖動操作時嘗試使用 Ctrl 或 Shift,以查看與地圖進行交互的其他方式。所有這些功能都是可定制的。

您的應用程式即將完成。在下一部分中,您將處理在地圖上選擇位置,並顯示所選位置的地址。您還將在頁面上顯示生成的 JSON,以查看完整結果。

您的應用程序的最後一步是在地圖上添加搜索。在這種情況下,您將添加反向地理編碼搜索,您可以在其中找到某個位置的項目。

注意

Amazon 定 Location Service 還提供按名稱或地址進行搜索的功能,以便在地圖上查找地點的位置。

將搜尋功能新增至您的應用程式
  1. 開啟您在上一節中建立的main.js檔案。

  2. 修改main函數,如圖所示。您需要進行的變更顯示在中green

    async function main() { // Create an authentication helper instance using an API key const authHelper = await amazonLocationAuthHelper.withAPIKey(apiKey); // Initialize map and Amazon Location SDK client: const map = await initializeMap(); const client = new amazonLocationClient.LocationClient({ region, ...authHelper.getLocationClientConfig(), // Provides configuration required to make requests to Amazon Location }); // On mouse click, display marker and get results: map.on("click", async function (e) { // Set up parameters for search call let params = { IndexName: placesName, Position: [e.lngLat.lng, e.lngLat.lat], Language: "en", MaxResults: "5", }; // Set up command to search for results around clicked point const searchCommand = new amazonLocationClient.SearchPlaceIndexForPositionCommand(params); try { // Make request to search for results around clicked point const data = await client.send(searchCommand); // Write JSON response data to HTML document.querySelector("#response").textContent = JSON.stringify(data, undefined, 2); // Display place label in an alert box alert(data.Results[0].Place.Label); } catch (error) { // Write JSON response error to HTML document.querySelector("#response").textContent = JSON.stringify(error, undefined, 2); // Display error in an alert box alert("There was an error searching."); } }); }

    此程式碼首先是設定 Amazon 位置身份驗證協助程式以使用您的 API 金鑰。

    const authHelper = await amazonLocationAuthHelper.withAPIKey(apiKey);

    然後,它會使用該身份驗證協助程式,以及您用來建立新 Amazon 位置用戶端的區域。

    const client = new amazonLocationClient.LocationClient({ region, ...authHelper.getLocationClientConfig(), });

    接下來,代碼響應用戶在地圖控件上選擇一個位置。它通過捕獲 MapLibre 提供的事件來做到這一點click

    map.on("click", async function(e) { ... });

    此 MapLibre click事件提供的參數包括使用者選擇的緯度和經度 (e.lngLat)。在click事件中,程式碼會建立searchPlaceIndexForPositionCommand以尋找指定緯度和經度的實體。

    // Set up parameters for search call let params = { IndexName: placesName, Position: [e.lngLat.lng, e.lngLat.lat], Language: "en", MaxResults: "5" }; // Set up command to search for results around clicked point const searchCommand = new amazonLocationClient.SearchPlaceIndexForPositionCommand(params); try { // Make request to search for results around clicked point const data = await client.send(searchCommand); ... });

    這裡IndexName是您先前建立的「放置索引」資源的名稱,Position也就是要搜尋的緯度和經度,Language是結果的偏好語言,並MaxResults告訴 Amazon Location 最多只傳回五個結果。

    剩餘的程式碼會檢查是否有錯誤,然後在呼叫的<pre>元素中顯示搜尋結果response,並在警告方塊中顯示最上層的結果。

  3. (選擇性) 如果您現在在瀏覽器中儲存並開啟quickstart.html檔案,在地圖上選擇一個位置將會顯示所選地點的名稱或地址。

  4. 應用程序中的最後一步是使用該 MapLibre 功能在用戶選擇的位置添加標記。修改main功能,如下所示。您需要進行的變更顯示在中green

    async function main() { // Create an authentication helper instance using an API key const authHelper = await amazonLocationAuthHelper.withAPIKey(apiKey); // Initialize map and Amazon Location SDK client const map = await initializeMap(); const client = new amazonLocationClient.LocationClient({ region, ...authHelper.getLocationClientConfig(), // Provides configuration required to make requests to Amazon Location }); // Variable to hold marker that will be rendered on click let marker; // On mouse click, display marker and get results: map.on("click", async function (e) { // Remove any existing marker if (marker) { marker.remove(); } // Render a marker on clicked point marker = new maplibregl.Marker().setLngLat([e.lngLat.lng, e.lngLat.lat]).addTo(map); // Set up parameters for search call let params = { IndexName: placesName, Position: [e.lngLat.lng, e.lngLat.lat], Language: "en", MaxResults: "5", }; // Set up command to search for results around clicked point const searchCommand = new amazonLocationClient.SearchPlaceIndexForPositionCommand(params); ...

    此代碼聲明一個marker變量,該變量在用戶每次選擇一個位置時填充,顯示他們選擇的位置。該標記是由地圖控件自動呈現,一旦它被添加到地圖與.addTo(map);。程式碼也會檢查先前的標記,並將其移除,以便一次螢幕上只有 1 個標記。

  5. 儲存main.js檔案,然後在瀏覽器中開啟quickstart.html檔案。您可以像以前一樣在地圖上平移和縮放,但是現在,如果您選擇位置,您將看到有關所選位置的詳細信息。

您的快速入門應用程式已完成。本教程向您展示瞭如何創建靜態 HTML 應用程序,該應用程序:

  • 建立使用者可以與之互動的地圖。

  • 處理地圖事件(click)。

  • 呼叫 Amazon 定 Location Service API,專門用於搜尋某個位置的地圖,使用searchPlaceIndexForPosition.

  • 使用地 MapLibre 圖控制項來加入標記。

查看最終申請

本節包含此應用程式的最終原始程式碼。您也可以在上找到最終專案 GitHub

您也可以在 GitHub上找到使用 Amazon Cognito 而非 API 金鑰的應用程式版本。

Overview

在此快速入門教學課程中,選取每個頁籤以檢視檔案的最終原始程式碼。

這些文件是:

  • quickstart.html — 您的應用程式的架構,包括地圖和搜尋結果的 HTML 元素持有者。

  • main.css — 應用程式的樣式表。

  • main.js — 用於驗證使用者、建立地圖以及搜尋事件的應用程式指令碼。click

quickstart.html

快速啟動應用程式的 HTML 架構。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Quick start tutorial</title> <!-- Styles --> <link href="https://unpkg.com/maplibre-gl@3.x/dist/maplibre-gl.css" rel="stylesheet" /> <link href="main.css" rel="stylesheet" /> </head> <body> ... <footer>This is a simple Amazon Location Service app. Pan and zoom. Click to see details about entities close to a point.</footer> <!-- JavaScript dependencies --> <script src="https://unpkg.com/maplibre-gl@3.x/dist/maplibre-gl.js"></script> <script src="https://unpkg.com/@aws/amazon-location-client@1.x/dist/amazonLocationClient.js"></script> <script src="https://unpkg.com/@aws/amazon-location-utilities-auth-helper@1.x/dist/amazonLocationAuthHelper.js"></script> <!-- JavaScript for the app --> <script src="main.js"></script> </body> </html>
main.css

快速啟動應用程式的樣式表。

* { box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; } body { margin: 0; } header { background: #000000; padding: 0.5rem; } h1 { margin: 0; text-align: center; font-size: 1.5rem; color: #ffffff; } main { display: flex; min-height: calc(100vh - 94px); } #map { flex: 1; } aside { overflow-y: auto; flex: 0 0 30%; max-height: calc(100vh - 94px); box-shadow: 0 1px 1px 0 #001c244d, 1px 1px 1px 0 #001c2426, -1px 1px 1px 0 #001c2426; background: #f9f9f9; padding: 1rem; } h2 { margin: 0; } pre { white-space: pre-wrap; font-family: monospace; color: #16191f; } footer { background: #000000; padding: 1rem; color: #ffffff; }
main.js

快速啟動應用程式的程式碼。紅色的文字應該以適當的 Amazon 位置物件名稱取代。

// Amazon Location Service resource names: const mapName = "explore.map"; const placesName = "explore.place"; const region = "your_region"; const apiKey = "v1.public.a1b2c3d4... // Initialize a map async function initializeMap() { // Initialize the map const mlglMap = new maplibregl.Map({ container: "map", // HTML element ID of map element center: [-77.03674, 38.891602], // Initial map centerpoint zoom: 16, // Initial map zoom style: `https://maps.geo.${region}.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor?key=${apiKey}`, // Defines the appearance of the map and authenticates using an API key }); // Add navigation control to the top left of the map mlglMap.addControl(new maplibregl.NavigationControl(), "top-left"); return mlglMap; } async function main() { // Create an authentication helper instance using an API key const authHelper = await amazonLocationAuthHelper.withAPIKey(apiKey); // Initialize map and Amazon Location SDK client const map = await initializeMap(); const client = new amazonLocationClient.LocationClient({ region, ...authHelper.getLocationClientConfig(), // Provides configuration required to make requests to Amazon Location }); // Variable to hold marker that will be rendered on click let marker; // On mouse click, display marker and get results: map.on("click", async function (e) { // Remove any existing marker if (marker) { marker.remove(); } // Render a marker on clicked point marker = new maplibregl.Marker().setLngLat([e.lngLat.lng, e.lngLat.lat]).addTo(map); // Set up parameters for search call let params = { IndexName: placesName, Position: [e.lngLat.lng, e.lngLat.lat], Language: "en", MaxResults: "5", }; // Set up command to search for results around clicked point const searchCommand = new amazonLocationClient.SearchPlaceIndexForPositionCommand(params); try { // Make request to search for results around clicked point const data = await client.send(searchCommand); // Write JSON response data to HTML document.querySelector("#response").textContent = JSON.stringify(data, undefined, 2); // Display place label in an alert box alert(data.Results[0].Place.Label); } catch (error) { // Write JSON response error to HTML document.querySelector("#response").textContent = JSON.stringify(error, undefined, 2); // Display error in an alert box alert("There was an error searching."); } }); } main();

下一步是什麼

您已完成快速入門教學課程,並且應該瞭解如何使用 Amazon 定 Location Service 來建置應用程式。要充分利用 Amazon 位置,您可以查看以下資源: