

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

# 创建您的第一个 Amazon Location 地图和地点应用程序
<a name="first-app"></a>

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

**先决条件：**

如果您已在[使用 Amazon Location Service 控制台进行身份验证](set-up-auth.md)步骤中创建 API 密钥，那么可以立即开始。

如果您尚未创建 API 密钥，请先遵循[使用 Amazon Location Service 控制台进行身份验证](set-up-auth.md)，然后继续构建应用程序。如有任何疑问，请参阅[使用 API 密钥进行身份验证](using-apikeys.md)和 [Amazon Location 支持的区域](location-regions.md)了解更多信息。

## Web
<a name="qs-web"></a>

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

### 设置初始页面
<a name="qs-initial-page"></a>

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

#### 添加所需的库和样式表
<a name="qs-initial-add-library"></a>

创建 `index.html` 文件。要渲染地图，你需要 MapLibre GL JS 和 MapLibre GL Geocoder。您将添加 MapLibre 和 Geocoder 样式表和脚本。 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@5.x/dist/maplibre-gl.css" />
    <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x/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>
```

#### 创建地图容器
<a name="qs-create-map-container"></a>

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

 将 `style.css` 和 `index.html` 文件保存在同一文件夹中。

 从中下载`style.css`文件[GitHub](https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/style.css)。

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

#### 添加 API 密钥和 AWS 区域详情
<a name="qs-create-add-key"></a>

将您在中[使用 API 密钥进行身份验证](using-apikeys.md)创建的 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>
```

### 向应用程序添加地图
<a name="qs-add-map"></a>

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

 如果尚未这样做，请从中下载该`style.css`文件[GitHub](https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/style.css)。

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

#### 创建一个函数来初始化地图
<a name="qs-initialize-map-function"></a>

要设置地图，请在行 `//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
}
```

#### 初始化地图
<a name="qs-initialize-map"></a>

调用 `initializeMap(...)` 以初始化地图。或者，可以在 `initializeMap` 函数之后，用您喜欢的样式和颜色方案对其进行初始化。有关更多样式选项，请参阅 [AWS 地图样式和功能](map-styles.md)。

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

#### 添加导航控件
<a name="qs-add-navigation"></a>

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

#### 查看地图代码
<a name="qs-add-final"></a>

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

### 向应用程序添加地点
<a name="qs-add-places"></a>

在本节中，我们将设置向应用程序添加地点功能。从下载 JavaScript 文件 GitHub，[https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/utils.js](https://github.com/aws-geospatial/amazon-location-samples-js/blob/quick_start_sample_js/quick-start/utils.js)。

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

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

#### 创建要创建的函数 GeoPlaces
<a name="qs-create-geoplaces"></a>

要添加搜索功能，请使用 `AuthHelper` 和 `AmazonLocationClient` 初始化 `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
}
```

#### 创建向应用程序添加搜索框的函数
<a name="qs-add-searchbox"></a>

在 `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
}
```

#### 向应用程序添加搜索框
<a name="qs-add-searchbox-to-application"></a>

按照第 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` 以查看其实际效果。

#### 添加在用户点击地图时显示弹出窗口的函数
<a name="qs-add-map-click-feature"></a>

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

#### 调用函数以添加地图点击功能
<a name="qs-call-map-click-feature"></a>

要启用地图点击操作，请在包含 `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);
```

#### 查看地图和地点应用程序
<a name="qs-review-places"></a>

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

### 了解更多
<a name="qs-whats-next"></a>

您已经完成了快速入门教程，应该对如何使用 Amazon Location Service 来构建应用程序有所了解。要了解更多关于 Amazon Location 的信息，您可以查看以下资源：
+ **查询建议详细信息** - 考虑扩展 `GeoPlaces` 类或使用与 `ReverseGeocode` 类似的方法，来获取有关 `Suggestion` API 返回的结果的更多详细信息。
+ **选择满足您业务需求的恰当 API** - 要确定最能满足您需求的 Amazon Location API，请查看此资源：[选择正确的 API](choose-an-api.md)。
+ **查看 Amazon Location“操作方法”指南** - 访问[《Amazon Location Service 开发人员指南》](https://docs.aws.amazon.com/location/)，获取教程和其他资源。
+ **文档和产品信息** - 如需获取完整文档，请访问[《Amazon Location Service 开发人员指南》](https://docs.aws.amazon.com/location/)。要了解有关该产品的更多信息，请前往 [Amazon Location Service 产品](https://aws.amazon.com/location)页面。