创建您的第一个 Amazon Location 地图和地点应用程序 - Amazon Location Service

创建您的第一个 Amazon Location 地图和地点应用程序

在本节中,您将使用地图和地点功能创建第一个应用程序。

先决条件:

如果您已在使用 Amazon Location Service 控制台进行身份验证步骤中创建 API 密钥,那么可以立即开始。

如果您尚未创建 API 密钥,请先遵循使用 Amazon Location Service 控制台进行身份验证,然后继续构建应用程序。如有任何疑问,请参阅使用 API 密钥进行身份验证Amazon Location 支持的区域了解更多信息。

以下是使用 MapLibre GL JS 创建 Amazon Location Service 地图应用程序的分步教程。本指南将引导您完成设置地图、添加样式设置选项和启用地点搜索功能的过程。

在本节中,我们将设置初始页面和文件夹结构。

添加所需的库和样式表

创建 index.html 文件。要渲染地图,您需要 MapLibre GL JS 和 MapLibre GL 地理编码器。您将添加 MapLibre 和地理编码器样式表以及 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@4.7.1/dist/maplibre-gl.css" /> <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/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>

创建地图容器

在 HTML 文件的 <body> 元素下,在 HTML 中创建一个用于保存地图的 <div> 元素。您可以在 CSS 中设置此 <div> 的样式,以根据应用程序需求设置尺寸。必须从我们的 GitHub 存储库中下载 CSS 文件 style.css。这将有助于您专注于业务逻辑。

style.cssindex.html 文件保存在同一文件夹中。

GitHub 下载 style.css 文件。

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

添加 API 密钥和 AWS 区域详细信息

将您在使用 API 密钥进行身份验证中创建的 API 密钥以及创建密钥时所在的 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>

在本节中,我们将向应用程序添加地图功能。开始之前,您的文件应采用以下文件夹结构。

如果尚未这样做,请从 GitHub 下载 style.css 文件。

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

创建一个函数来初始化地图

要设置地图,请在行 //Add functions 后创建函数 initializeMap(...)

选择初始中心位置和缩放级别。在本示例中,我们将地图的中心定位在加拿大温哥华,缩放级别为 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 }

初始化地图

调用 initializeMap(...) 以初始化地图。或者,可以在 initializeMap 函数之后,用您喜欢的样式和颜色方案对其进行初始化。有关更多样式选项,请参阅 AWS 地图样式和自定义

// 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 以查看地图的实际效果。

添加导航控件

或者,可以向地图添加导航控件(缩放和旋转)。这应在调用 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

查看地图代码

恭喜您!您的第一个应用程序已准备好使用地图。在浏览器中打开 index.html。确保 style.cssindex.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@4.7.1/dist/maplibre-gl.css" /> <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/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>

在本节中,我们将设置向应用程序添加地点功能。从 GitHub 下载 JavaScript 文件 utils.js

开始之前,您的文件应采用以下文件夹结构:

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

创建用于创建 GeoPlaces 的函数

要添加搜索功能,请使用 AuthHelperAmazonLocationClient 初始化 GeoPlaces 类。在 index.html 中的 </script> 标签前添加以下 getGeoPlaces(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 }

index.html 中的 </script> 标签前添加以下 addSearchBox(map, geoPlaces)renderPopup(feature)createPopup(feature) 函数,以完成搜索功能设置。

/** * 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 }

向应用程序添加搜索框

按照第 3.1 节中的定义,通过调用 getGeoPlaces(map) 来创建 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 以查看其实际效果。

添加在用户点击地图时显示弹出窗口的函数

创建在用户点击地图时显示弹出窗口的函数 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 } }); }

调用函数以添加地图点击功能

要启用地图点击操作,请在包含 addSearchBox(map, geoPlaces) 的行之后调用 addMapClick(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);

查看地图和地点应用程序

恭喜您!您的第一个应用程序已准备就绪,可以使用地图和地点。在浏览器中打开 index.html。确保 style.cssutils.jsindex.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@4.7.1/dist/maplibre-gl.css" /> <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/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>

您已经完成了快速入门教程,应该对如何使用 Amazon Location Service 来构建应用程序有所了解。要了解更多关于 Amazon Location 的信息,您可以查看以下资源: