本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
建立網路應用程式
在本節中,您將創建一個靜態網頁,其中包含地圖和在某個位置進行搜索的功能。首先,您將創建您的 Amazon 位置資源,並為您的應用程序創建一個API密鑰。
為您的應用程式建立 Amazon 位置資源
如果您還沒有這些資源,則必須建立應用程式將使用的 Amazon 位置資源。在這裡,您可以創建一個地圖資源以在應用程序中顯示地圖,並創建地圖索引以在地圖上搜索位置。
將位置資源新增至您的應用程式
-
選擇您要使用的地圖樣式。
-
在 Amazon 位置主控台的「地圖
」頁面上,選擇「建立地圖」以預覽地圖樣式。 -
為新地圖資源新增「名稱」和「描述」。記下您用於地圖資源的名稱。稍後在自學課程中建立腳本檔案時,您將需要它。
-
選擇地圖。
注意
選擇地圖型式也會選擇您將使用的地圖資料提供者。如果您的應用程式正在追蹤或路由您在業務中使用的資產 (例如送貨車輛或員工),您只能用HERE作地理位置提供者。如需詳細資訊,請參閱AWS 服務條款
第 82 節。 -
同意 Amazon 位置條款與條件,然後選擇「建立地圖」。您可以與選擇的地圖互動:放大、縮小或向任何方向平移。
-
記下為您的新地圖資源顯示的 Amazon 資源名稱 (ARN)。您將在本教程稍後使用它來創建正確的身份驗證。
-
-
選擇您要使用的位置索引。
-
在「放置索引
」頁面上的 Amazon 位置主控台中,選擇「建立位置索引」。 -
新增位置索引資源的「名稱」和「說明」。記下您用於放置索引資源的名稱。稍後在自學課程中建立腳本檔案時,您將需要它。
-
選擇資料提供者。
注意
在大多數情況下,請選擇與您已選擇的地圖提供者相符的資料提供者。這有助於確保搜索將匹配地圖。
如果您的應用程式正在追蹤或路由您在業務中使用的資產 (例如送貨車輛或員工),您只能用HERE作地理位置提供者。如需詳細資訊,請參閱AWS 服務條款
第 82 節。 -
選擇數據存儲選項。在本自學課程中,不會儲存結果,因此您可以選擇「否,僅限單次使用」。
-
同意 Amazon 地點條款與條件,然後選擇建立地點索引。
-
記下ARN新地點索引資源所顯示的內容。您將在本教程的下一部分中使用它來創建正確的身份驗證。
-
為您的應用程式設定驗證
您在本教程中創建的應用程序具有匿名用法,這意味著您的用戶不需 AWS 要登錄即可使用該應用程序。但是,根據預設,Amazon 定 Location Service APIs 需要身份驗證才能使用。您可以使用 Amazon Cognito 或API金鑰為匿名使用者提供身份驗證和授權。在本教學課程中,您將建立在範例應用程式中使用的API金鑰。
注意
如需將API金鑰或 Amazon Cognito 與 Amazon 定 Location Service 搭配使用的詳細資訊,請參閱授予對 Amazon 定 Location Service 的訪問。
若要為您的應用程式設定驗證
-
轉到 Amazon 位置控制台
,然後從左側菜單中選擇API鍵。 -
選擇建立API金鑰。
重要
您建立的API金鑰必須 AWS 帳戶 與您在上一節中建立的 Amazon 定 Location Service 資源所在的 AWS 區域相同。
-
一個創建API鍵頁面,填寫以下信息。
-
名稱 — API 金鑰的名稱,例如
MyWebAppKey
。 -
資源 — 選擇您在上一節中建立的 Amazon 位置圖和放置索引資源。您可以選擇 [新增資源] 來新增多個資源。這將允許API密鑰與這些資源一起使用。
-
動作 — 指定您要使用此API金鑰授權的動作。您必須至少選取 geo: GetMap * 和 geo:,這SearchPlaceIndexfForPosition樣教學課程才能如預期般運作。
-
您可以選擇性地將「描述」、「到期時間」或「標籤」新增至API金鑰。您還可以添加引用者(例如
*.example.com
),將密鑰限制為僅從特定域中使用。這意味著該教程將僅適用於該域。注意
建議您通過設置到期時間或API引用者(如果不是兩者)來保護您的密鑰使用情況。
-
-
選擇建立API金鑰以建立API金鑰。
-
選擇 [顯示API金鑰],然後複製機碼值以供稍後在自學課程中使用。它將以形式出現
v1.public.
。a1b2c3d4...
重要
在本教程稍後為您的應用程序編寫代碼時,您將需要此密鑰。
HTML為您的應用程式建立
在本教程中,您將創建一個嵌入地圖的靜態HTML頁面,並允許用戶查找地圖上的某個位置。該應用程序將由三個文件組成:網頁的CSS文件和文件,以及一個 JavaScript (.js)文件,用於創建地圖並響應用戶的交互和地圖事件的代碼。HTML
首先,讓我們創建將用於應用程序的HTML和CSS框架。這將是一個簡單的頁面,其中包含一個<div>
元素來保存地圖容器和一個<pre>元素來顯示您的查詢的JSON響應。
若要HTML為您的快速入門應用程式建立
-
建立稱為
quickstart.html
的新檔案。 -
在您選擇的文字編輯器或環境中編輯檔案。將以下內容添加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">
元素,這將顯示在地圖上搜索的結果。 -
儲存您的檔案。
現在添CSS加網頁。這將設置應用程序的文本和佔位符元素的樣式。
若要CSS為您的快速入門應用程式建立
-
在與先前程序中建立的 quickstart.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; }
這將地圖設置為填充其他任何東西未使用的空間,將我們的響應區域設置為佔用應用程序寬度的 30%,並為標題和說明性文本設置顏色和樣式。
-
儲存檔案。
-
現在,您可以在瀏覽器中查看
quickstart.html
文件以查看應用程序的佈局。
接下來,您將地圖控制項新增至應用程式。
將交互式地圖添加到您的應用程序
現在您有架構和 div 預留位置,您可以將地圖控制項新增至應用程式。本教程使用 MapLibre GL JS
若要將互動式地圖加入至您的應用程式
-
開啟您在上一節中建立的
quickstart.html
檔案。 -
將參考新增至所需程式庫,以及您要建立的指令碼檔案。您需要進行的變更顯示在中
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 位置客戶端是基 AWS SDK於 JavaScript v3。
-
Amazon 位置身份驗證助手 這提供了有用的功能,可用於使用API金鑰或 Amazon Cognito 驗證 Amazon 定 Location Service。
此步驟也會新增參照
main.js
,您將在下一步建立該參照。 -
-
儲存
quickstart.html
檔案。 -
在HTML與和檔案相同的資料夾
main.js
中建立一個名為的新檔CSS案,然後將其開啟以進行編輯。 -
將以下腳本添加到您的文件中。中的文字
red
應該替換為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容器,它使用在我們的地圖 div 元素HTML。
-
地圖的初始中心到華盛頓特區的一個點。
-
縮放層級為 16 (縮放至鄰近或圖塊層級)。
-
用於地圖的樣式,可 MapLibre 用於獲取地圖框和其他用於渲染地圖的信息。URL請注意,這URL包括用於驗證的API密鑰。
-
-
儲存 JavaScript 檔案,然後使用瀏覽器開啟檔案。現在,您的頁面上有一個地圖,您可以在其中使用平移和縮放動作。
注意
您可以使用此應用程序來查看 MapLibre 地圖控件的行為。您可以在使用拖動操作時嘗試使用 Ctrl 或 Shift,以查看與地圖進行交互的其他方式。所有這些功能都是可定制的。
您的應用程式即將完成。在下一部分中,您將處理在地圖上選擇位置,並顯示所選位置的地址。您還將在頁面JSON上顯示結果,以查看完整結果。
新增搜尋到您的應用程式
您的應用程序的最後一步是在地圖上添加搜索。在這種情況下,您將添加反向地理編碼搜索,您可以在其中找到某個位置的項目。
注意
Amazon 定 Location Service 還提供按名稱或地址進行搜索的功能,以便在地圖上查找地點的位置。
若要新增搜尋功能至您的應用程式
-
開啟您在上一節中建立的
main.js
檔案。 -
修改
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
,並在警告方塊中顯示最上層的結果。 -
(選擇性) 如果您現在在瀏覽器中儲存並開啟
quickstart.html
檔案,在地圖上選擇一個位置將會顯示所選地點的名稱或地址。 -
應用程序中的最後一步是使用該 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 個標記。 -
儲存
main.js
檔案,然後在瀏覽器中開啟quickstart.html
檔案。您可以像以前一樣在地圖上平移和縮放,但是現在,如果您選擇位置,您將看到有關所選位置的詳細信息。
您的快速入門應用程式已完成。本教程向您展示瞭如何創建靜態HTML應用程序:
-
建立使用者可以與之互動的地圖。
-
處理地圖事件(
click
)。 -
撥打 Amazon 定 Location ServiceAPI,專門用於搜索某個位置的地圖,使用
searchPlaceIndexForPosition
. -
使用地 MapLibre 圖控制項來加入標記。
查看最終申請
本節包含此應用程式的最終原始程式碼。您也可以在上找到最終專案 GitHub
您也可以找到使用 Amazon Cognito 而非開啟API GitHub
下一步是什麼
您已完成快速入門教學課程,並且應該瞭解如何使用 Amazon 定 Location Service 來建置應用程式。要充分利用 Amazon 位置,您可以查看以下資源: