创建 Web 应用程序 - Amazon Location Service

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

创建 Web 应用程序

在本部分中,您将创建一个静态网页,其中包含地图并能够在某个位置进行搜索。首先,您将创建您的 Amazon Location 资源并为您的应用程序创建 API 密钥。

为您的应用程序创建 Amazon Location 资源

如果您还没有,则必须创建应用程序将使用的 Amazon Location 资源。在这里,您可以创建用于在应用程序中显示地图的地图资源,以及用于在地图上搜索位置的地点索引。

向您的应用程序添加位置资源
  1. 选择要使用的地图样式。

    1. 在 Amazon Location 控制台的地图页面上,选择创建地图以预览地图样式。

    2. 为新地图资源添加名称描述。记下您用于地图资源的名称。在本教程的后面部分创建脚本文件时,您将需要它。

    3. 选择一张地图。

      注意

      选择地图样式还会选择要使用的地图数据提供程序。如果您的应用程序正在跟踪或路由您在企业中使用的资产,例如运载车辆或员工,则只能使用 HERE 作为地理位置提供程序。想要了解更多信息,请参阅 AWS 服务条款的第 82 节。

    4. 同意 Amazon Location 条款和条件,然后选择创建地图。您可以与所选地图进行交互:放大、缩小或向任意方向平移。

    5. 请记下新地图资源显示的 Amazon 资源名称 (ARN)。在本教程的后面部分,您将使用它来创建正确的身份验证。

  2. 选择要使用的地点索引。

    1. 在 Amazon Location 控制台的地点索引页面上,选择创建地点索引

    2. 为新的地点索引资源添加名称描述。记下地点索引资源使用的名称。在本教程的后面部分创建脚本文件时,您将需要它。

    3. 选择数据提供程序。

      注意

      在大多数情况下,请选择与您已选择的地图提供程序相匹配的数据提供程序。这有助于确保搜索结果与地图相匹配。

      如果您的应用程序正在跟踪或路由您在企业中使用的资产,例如运载车辆或员工,则只能使用 HERE 作为地理位置提供程序。想要了解更多信息,请参阅 AWS 服务条款的第 82 节。

    4. 选择数据存储选项。在本教程中,不存储结果,因此您可以选择否,仅限一次性使用

    5. 同意 Amazon Location 条款和条件,然后选择创建地点索引

    6. 记下为您的新地点索引资源显示的 ARN。在本教程的下一部分中,您将使用它来创建正确的身份验证。

为应用程序设置身份验证

您在本教程中创建的应用程序是匿名使用的,这意味着您的用户无需登录 AWS 即可使用该应用程序。但是,默认情况下,Amazon Location Service API 需要身份验证才能使用。您可以使用 Amazon Cognito 或 API 密钥为匿名用户提供身份验证和授权。在本教程中,您将创建用于示例应用程序的 API 密钥。

注意

有关使用 API 密钥或将 Amazon Cognito 与 Amazon Location Service 配合使用的更多信息,请参阅 授予对 Amazon Location Service 的访问权限

为您的应用程序设置身份验证
  1. 前往 Amazon Location 控制台,然后从左侧菜单中选择 API 密钥

  2. 选择创建 API 密钥

    重要

    您创建的 API 密钥必须与您在上一部分中创建的 Amazon Location Service 资源位于同一 AWS 账户 和 AWS 区域。

  3. 创建 API 密钥页面上,填写以下信息。

    • 名称——您的 API 密钥的名称,例如 MyWebAppKey

    • 资源——选择您在上一部分中创建的 Amazon Location Map 和地点索引资源。您可以通过选择添加资源来添加多个资源。这将允许将 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 框架。这将是一个简单的页面,其中包含一个用于存放地图容器的 <div> 元素和一个用于显示查询的 JSON 响应的 <pre> 元素。

为快速入门应用程序创建 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 获取数据。您还将使用 身份验证帮助程序 来简化使用您的 API 密钥签署对 Amazon Location 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 Location 客户端。这为获取地图数据和在地图上搜索地点所需的 Amazon Location 功能提供了接口。Amazon Location 客户端基于适用于 JavaScript v3 的AWS软件开发工具包。

    • Amazon Location 认证帮助程序。这为使用 API 密钥或 Amazon Cognito 对 Amazon 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 Location 资源,然后配置和初始化 MapLibre GL JS 地图控件,并将其放置在带有 ID 的<div>元素中。map

    理解 initializeMap() 函数很重要。它会创建一个新的 MapLibre 地图控件(mapmlglMap本地调用,但在代码的其余部分中调用),用于在应用程序中渲染地图。

    // 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 Location 身份验证帮助程序以使用您的 API 密钥。

    const authHelper = await amazonLocationAuthHelper.withAPIKey(apiKey);

    然后,它会使用该身份验证帮助程序以及您用来创建新的 Amazon Location 客户端的区域。

    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 最多只返回五个结果。

    其余代码检查是否存在错误,然后在名为 response<pre> 元素中显示搜索结果,并在警告框中显示最上面的结果。

  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。

您还可以在上找到使用 Amazon Cognito 而不是 API 密钥的应用程序版本。 GitHub

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 Location 对象名称。

// 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 Location 的信息,您可以查看以下资源: