Crie seu primeiro aplicativo Amazon Location Maps and Places - Amazon Location Service

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á.

Crie seu primeiro aplicativo Amazon Location Maps and Places

Nesta seção, você criará seu primeiro aplicativo com o Maps and Places.

Pré-requisito:

Se você já criou uma chave de API nas Use o console do Amazon Location Service para autenticar etapas, vamos começar.

Se você ainda não criou uma chave de API, siga Use o console do Amazon Location Service para autenticar antes de continuar a criar o aplicativo. Se você tiver alguma dúvida, consulte Use chaves de API para autenticar e Regiões suportadas pela 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 orientará você na configuração do mapa, na adição de opções de estilo e na ativação da funcionalidade de pesquisa de lugares.

Nesta seção, configuraremos a estrutura inicial da página e da pasta.

Adicione as 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 em seu index.html arquivo.

<!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>

Crie o contêiner de mapa

Sob o <body> elemento do arquivo HTML, crie um <div> elemento em seu HTML para conter o mapa. Você pode estilizar isso <div> em seu CSS para definir dimensões conforme necessário para seu aplicativo. 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 index.html arquivos style.css e 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 Use chaves de API para 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, adicionaremos recursos de mapa ao aplicativo. Antes de começar, seus arquivos devem estar nessa 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]

Crie uma função para inicializar o mapa

Para configurar seu mapa, crie a seguinte função,initializeMap(...), após a linha//Add functions.

Escolha uma localização central inicial e um nível de zoom. Neste exemplo, definimos o centro do mapa para Vancouver, Canadá, com um nível de zoom de 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

Ligue initializeMap(...) para inicializar o mapa. Opcionalmente, você pode inicializá-lo com seu estilo e esquema de cores preferidos após a initializeMap função. Para obter mais opções de estilo, consulteAWS estilos e personalização de mapas.

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

Opcionalmente, você pode adicionar controles de navegação (zoom e rotação) ao mapa. Isso deve ser feito depois de ligarinitializeMap(...).

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

Revise o código do mapa

Parabéns! Seu primeiro aplicativo está pronto para usar um mapa. Abra index.html em um navegador. Verifique se style.css está na mesma pasta queindex.html.

Seu HTML final deve ter a seguinte aparência:

<!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, configuraremos os recursos de adição de lugares ao aplicativo. Baixe o JavaScript arquivo em GitHub, utils.js.

Antes de começar, seus arquivos devem estar nessa estrutura de pastas:

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

Criar função para criar GeoPlaces

Para adicionar a funcionalidade de pesquisa, inicialize a GeoPlaces classe usando AuthHelper e. AmazonLocationClient Adicione a getGeoPlaces(map) função a seguir antes da </script> entrada da tagindex.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 }

Adicione as seguintes createPopup(feature) funções addSearchBox(map, geoPlaces)renderPopup(feature),, e antes da </script> tag 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 ao aplicativo

Crie um GeoPlaces objeto chamando getGeoPlaces(map) conforme definido na Seção 3.1 e, em seguida, chame addSearchBox(map, geoPlaces) para adicionar a caixa de pesquisa ao aplicativo.

// 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);

Sua pesquisa de lugares está pronta para ser usada. Abra index.html em um navegador para vê-lo em ação.

Adicionar função para mostrar pop-up ao clicar do usuário 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 </script> tag.

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

Função de chamada para adicionar recurso de clique no mapa

Para ativar a ação de clique no mapa, chame addMapClick(map, geoPlaces) após a linha que contémaddSearchBox(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);

Revise o aplicativo Maps and Places

Parabéns! Seu primeiro aplicativo está pronto para usar o Maps and Places. Abra index.html em um navegador. Certifique-se style.css de que utils.js estão na mesma pasta comindex.html.

Seu HTML final deve ter a seguinte aparência:

<!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: considere estender a GeoPlaces classe ou usar uma abordagem semelhante ReverseGeocode para obter mais detalhes sobre os resultados retornados pela Suggestion API.

  • Escolha a API certa para suas necessidades comerciais - Para determinar a melhor API de localização da Amazon para suas necessidades, confira este recurso:Escolha a API certa.

  • Confira os guias de “instruções” de localização da Amazon - Visite o Guia do desenvolvedor do Amazon Location Service para ver tutoriais e mais recursos.

  • Documentação e informações sobre o produto — Para obter a documentação completa, visite o Amazon Location Service Developer Guide. Para saber mais sobre o produto, acesse a página do produto Amazon Location Service.