

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# 使用 Location Service Places 的代码示例 AWS SDKs
<a name="geo-places_code_examples"></a>

以下代码示例向您展示了如何使用带有 AWS 软件开发套件 (SDK) 的 Amazon Location Service Places。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

**更多资源**
+  **[ Location Service Places 开发人员指南](https://docs.aws.amazon.com/location/latest/developerguide/places.html)**——有关 Location Service Places 的更多信息。
+ **[Location Service Places API 参考](https://docs.aws.amazon.com/location/latest/APIReference/Welcome.html)**——有关所有可用的 Location Service Places 操作的详细信息。
+ **[AWS 开发者中心](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** — 您可以按类别或全文搜索筛选的代码示例。
+ **[AWS SDK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 包含首选语言完整代码的 GitHub 存储库。包括有关设置和运行代码的说明。

**Contents**
+ [基本功能](geo-places_code_examples_basics.md)
  + [操作](geo-places_code_examples_actions.md)
    + [`ReverseGeocode`](geo-places_example_geo-places_ReverseGeocode_section.md)
    + [`SearchNearby`](geo-places_example_geo-places_SearchNearby_section.md)
    + [`SearchText`](geo-places_example_geo-places_SearchText_section.md)

# 使用 Location Service Places 的基本示例 AWS SDKs
<a name="geo-places_code_examples_basics"></a>

以下代码示例展示了如何使用 Amazon Location Service Places 的基础知识 AWS SDKs。

**Contents**
+ [操作](geo-places_code_examples_actions.md)
  + [`ReverseGeocode`](geo-places_example_geo-places_ReverseGeocode_section.md)
  + [`SearchNearby`](geo-places_example_geo-places_SearchNearby_section.md)
  + [`SearchText`](geo-places_example_geo-places_SearchText_section.md)

# 使用 Location Service 地点的操作 AWS SDKs
<a name="geo-places_code_examples_actions"></a>

以下代码示例演示了如何使用执行各个 Location Service Places 操作 AWS SDKs。每个示例都包含一个指向的链接 GitHub，您可以在其中找到有关设置和运行代码的说明。

 以下示例仅包括最常用的操作。有关完整列表，请参阅 [Amazon Location Service 位置 API 参考](https://docs.aws.amazon.com/location/latest/APIReference/Welcome.html)。

**Topics**
+ [`ReverseGeocode`](geo-places_example_geo-places_ReverseGeocode_section.md)
+ [`SearchNearby`](geo-places_example_geo-places_SearchNearby_section.md)
+ [`SearchText`](geo-places_example_geo-places_SearchText_section.md)

# 与 AWS SDK `ReverseGeocode` 配合使用
<a name="geo-places_example_geo-places_ReverseGeocode_section"></a>

以下代码示例演示了如何使用 `ReverseGeocode`。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Performs reverse geocoding using the AWS Geo Places API.
     * Reverse geocoding is the process of converting geographic coordinates (latitude and longitude) to a human-readable address.
     * This method uses the latitude and longitude of San Francisco as the input, and prints the resulting address.
     */
    public CompletableFuture<ReverseGeocodeResponse> reverseGeocode() {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        logger.info("Use latitude 37.7749 and longitude -122.4194");

        // AWS expects [longitude, latitude].
        List<Double> queryPosition = List.of(longitude, latitude);
        ReverseGeocodeRequest request = ReverseGeocodeRequest.builder()
            .queryPosition(queryPosition)
            .build();
        CompletableFuture<ReverseGeocodeResponse> futureResponse =
            getGeoPlacesClient().reverseGeocode(request);

        return futureResponse.whenComplete((response, exception) -> {
            if (exception != null) {
                Throwable cause = exception.getCause();
                if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                    throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                }
                throw new CompletionException("Error performing reverse geocoding", exception);
            }

            response.resultItems().forEach(result ->
                logger.info("The address is: " + result.address().label())
            );
        });
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[ReverseGeocode](https://docs.aws.amazon.com/goto/SdkForJavaV2/geo-places-2020-11-19/ReverseGeocode)*中的。

------

# 与 AWS SDK `SearchNearby` 配合使用
<a name="geo-places_example_geo-places_SearchNearby_section"></a>

以下代码示例演示了如何使用 `SearchNearby`。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Performs a nearby places search based on the provided geographic coordinates (latitude and longitude).
     * The method sends an asynchronous request to search for places within a 1-kilometer radius of the specified location.
     * The results are processed and printed once the search completes successfully.
     */
    public CompletableFuture<SearchNearbyResponse> searchNearBy() {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        List<Double> queryPosition = List.of(longitude, latitude);

        // Set up the request for searching nearby places.
        SearchNearbyRequest request = SearchNearbyRequest.builder()
            .queryPosition(queryPosition)  // Set the position
            .queryRadius(1000L)  // Radius in meters (1000 meters = 1 km).
            .build();

        return getGeoPlacesClient().searchNearby(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                        throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error performing place search", exception);
                }

                // Process the response and print the results.
                response.resultItems().forEach(result -> {
                    logger.info("Place Name: " + result.placeType().name());
                    logger.info("Address: " + result.address().label());
                    logger.info("Distance: " + result.distance() + " meters");
                    logger.info("-------------------------");
                });
            });
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[SearchNearby](https://docs.aws.amazon.com/goto/SdkForJavaV2/geo-places-2020-11-19/SearchNearby)*中的。

------

# 与 AWS SDK `SearchText` 配合使用
<a name="geo-places_example_geo-places_SearchText_section"></a>

以下代码示例演示了如何使用 `SearchText`。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Searches for a place using the provided search query and prints the detailed information of the first result.
     *
     * @param searchQuery the search query to be used for the place search (ex, coffee shop)
     */
    public CompletableFuture<Void> searchText(String searchQuery) {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        List<Double> queryPosition = List.of(longitude, latitude);

        SearchTextRequest request = SearchTextRequest.builder()
                .queryText(searchQuery)
                .biasPosition(queryPosition)
                .build();

        return getGeoPlacesClient().searchText(request)
                .thenCompose(response -> {
                    if (response.resultItems().isEmpty()) {
                        logger.info("No places found.");
                        return CompletableFuture.completedFuture(null);
                    }

                    // Get the first place ID
                    String placeId = response.resultItems().get(0).placeId();
                    logger.info("Found Place with id: " + placeId);

                    // Fetch detailed info using getPlace
                    GetPlaceRequest getPlaceRequest = GetPlaceRequest.builder()
                            .placeId(placeId)
                            .build();

                    return getGeoPlacesClient().getPlace(getPlaceRequest)
                            .thenAccept(placeResponse -> {
                                logger.info("Detailed Place Information:");
                                logger.info("Name: " + placeResponse.placeType().name());
                                logger.info("Address: " + placeResponse.address().label());

                                if (placeResponse.foodTypes() != null && !placeResponse.foodTypes().isEmpty()) {
                                    logger.info("Food Types:");
                                    placeResponse.foodTypes().forEach(foodType -> {
                                        logger.info("  - " + foodType);
                                    });
                                } else {
                                    logger.info("No food types available.");
                                }
                                logger.info("-------------------------");
                            });
                })
                .exceptionally(exception -> {
                    Throwable cause = exception.getCause();
                    if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                        throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error performing place search", exception);
                });
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[SearchText](https://docs.aws.amazon.com/goto/SdkForJavaV2/geo-places-2020-11-19/SearchText)*中的。

------