As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Criar sua primeira aplicação de Mapas e Locais do Amazon Location
Nesta seção, você criará sua primeira aplicação com Mapas e Locais.
Pré-requisito:
Se você já criou uma chave de API nas etapas Usar o console do Amazon Location Service para se autenticar, vamos começar.
Se você ainda não criou uma chave de API, siga Usar o console do Amazon Location Service para se autenticar antes de continuar a criar a aplicação. Se você tiver dúvidas, consulte Usar chaves de API para se autenticar e Regiões do Amazon Location para obter mais informações.
Aqui está um step-by-step tutorial para criar um aplicativo de mapas do Amazon Location Service com o MapLibre GL JS. Este guia traz orientações para configurar o mapa, adicionar opções de estilo e habilitar as funcionalidades de pesquisa de lugares.
Nesta seção, vamos configurar a estrutura inicial de página e pasta.
Adicionar bibliotecas e folhas de estilo necessárias
Criar um arquivo index.html Para renderizar o mapa, você precisa do MapLibre GL JS e do GL MapLibre Geocoder. Você adicionará as folhas de estilo MapLibre e scripts do Geocoder. JavaScript
Copie e cole o código a seguir no arquivo 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>
Criar o contêiner do mapa
No elemento <body> do arquivo HTML, crie um elemento <div> em seu HTML para conter o mapa. Você pode estilizar <div> em seu CSS para definir dimensões conforme necessário para sua aplicação. Você deve baixar o arquivo CSS,style.css, do nosso GitHub repositório. Isso ajudará você a se concentrar na lógica de negócios.
Salve os arquivos style.css e index.html na mesma pasta.
Baixe o style.css arquivo em GitHub
<main role="main" aria-label="Map Container"> <div id="map"></div> </main>
Adicionar detalhes da chave de API e AWS da região
Adicione a chave de API que você criou Usar chaves de API para se autenticar a esse arquivo, junto com a AWS região em que a chave foi criada.
<!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>
Nesta seção, vamos adicionar recursos de mapa à aplicação. Antes de começar, seus arquivos devem estar nesta estrutura de pastas.
Se ainda não tiver feito isso, baixe o style.css arquivo em GitHub
|---FirstApp [Folder] |-------------- index.html [File] |-------------- style.css [File]
Criar uma função para inicializar o mapa
Para configurar seu mapa, crie a função initializeMap(...) depois da linha //Add functions.
Escolha uma localização central inicial e um nível de zoom. Neste exemplo, definimos o centro do mapa como Vancouver, Canadá, com nível de zoom 10. Adicione controles de navegação para facilitar o zoom.
/** * 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 }
Inicializar o mapa
Chame initializeMap(...) para inicializar o mapa. Você também pode inicializá-lo com seu estilo e esquema de cores preferidos após a função initializeMap. Para obter mais opções de estilo, consulte AWS estilos e recursos do mapa.
// 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
Abra index.html em um navegador para ver o mapa em ação.
Adicionar controle de navegação
Como opção, você pode adicionar controles de navegação (zoom e rotação) ao mapa. Faça isso depois de chamar 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
Revisar o código do mapa
Parabéns! Sua primeira aplicação está pronta para usar um mapa. Em um navegador, abra index.html. Verifique se style.css está na mesma pasta que index.html.
O arquivo HTML final deve estar assim:
<!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>
Nesta seção, vamos configurar recursos de locais à aplicação. Baixe o JavaScript arquivo em GitHub, utils.js
Antes de começar, seus arquivos devem estar nesta estrutura de pastas:
|---FirstApp [Folder] |-------------- index.html [File] |-------------- style.css [File] |-------------- utils.js [File]
Criar função para criar GeoPlaces
Para adicionar funcionalidades de pesquisa, inicialize a classe GeoPlaces usando AuthHelper e AmazonLocationClient. Adicione a função getGeoPlaces(map) a seguir antes da tag </script> em 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 }
Criar função para adicionar a caixa de pesquisa à aplicação
Adicione as funções addSearchBox(map, geoPlaces), renderPopup(feature) e createPopup(feature) antes da tag </script> em index.html para concluir a configuração da funcionalidade de pesquisa.
/** * 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 }
Adicionar caixa de pesquisa à aplicação
Crie um objeto GeoPlaces chamando getGeoPlaces(map), conforme definido na Seção 3.1, depois chame addSearchBox(map, geoPlaces) para adicionar a caixa de pesquisa à aplicação.
// 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);
A pesquisa de local está pronta para ser usada. Abra index.html em um navegador para vê-la em ação.
Adicionar função para mostrar pop-up quando o usuário clicar no mapa
Crie uma função addMapClick(map, geoPlaces) para exibir um pop-up quando o usuário clicar no mapa. Adicione essa função logo antes da tag </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 } }); }
Chamar função para adicionar atributo de clique no mapa
Para ativar a ação de clique no mapa, chame addMapClick(map, geoPlaces) depois da linha que contém 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);
Revisar a aplicação de Mapas e Locais
Parabéns! Sua primeira aplicação está pronta para usar Mapas e Locais. Em um navegador, abra index.html. Verifique se style.css e utils.js estão na mesma pasta com index.html.
O arquivo HTML final deve estar assim:
<!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>
Você concluiu o tutorial de início rápido e deve ter uma ideia de como o Amazon Location Service é usado para criar aplicativos. Para aproveitar melhor o Amazon Location, você pode conferir os seguintes recursos:
-
Detalhes da sugestão de consulta: estenda a classe
GeoPlacesou use uma abordagem semelhante aReverseGeocodepara obter mais detalhes sobre os resultados retornados pela APISuggestion. -
Escolha a API certa para as necessidades da sua empresa: para determinar a melhor API do Amazon Location para suas necessidades, confira este recurso: Escolher a API certa.
-
Consulte os guias de “instruções” do Amazon Location: acesse o Guia do desenvolvedor do Amazon Location Service para encontrar tutoriais e mais recursos.
-
Documentação e informações sobre o produto: para ver a documentação completa, acesse o Guia do desenvolvedor do Amazon Location Service. Para saber mais sobre o produto, acesse a página do produto Amazon Location Service
.