是否存在从坐标(纬度,经度)获取城市和国家名称的简单方法?没有 Google Maps API 可以做到吗?

问题描述 投票:0回答:1

我编写 Spring Boot 电报机器人。现在我有用户的经度和纬度,并想通过其获取城市和县名称。

尝试通过 Google Maps API 以及此处的示例获取 id,但没有 clientId 并且我的密钥由于某种原因无效。

java spring spring-boot google-maps geolocation
1个回答
0
投票

对于生产中的实际应用程序,您应该使用 API 密钥来解决问题。但如果您只是测试和玩玩,有一些免费服务不需要 API 密钥。尝试例如免费地理编码 API

您可以使用以下示例代码作为起点:

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {

    private static final String GEOCODING_RESOURCE = "https://geocode.maps.co/reverse";

    public static void main(String[] args) throws IOException, InterruptedException {

        ObjectMapper mapper = new ObjectMapper();

        String response = reverseGeocode("40.7558017", "-73.9787414");
        JsonNode responseJsonNode = mapper.readTree(response);

        JsonNode address = responseJsonNode.get("address");
        String city = address.get("city").asText();
        String country = address.get("country").asText();
        System.out.println("Reverse geocoding returned: " + city + ", " + country);
    }

    public static String reverseGeocode(String lat, String lon) throws IOException, InterruptedException {

        HttpClient httpClient = HttpClient.newHttpClient();
        String requestUri = GEOCODING_RESOURCE + "?lat=" + lat + "&lon=" + lon;
        HttpRequest geocodingRequest = HttpRequest.newBuilder()
                                                  .GET()
                                                  .uri(URI.create(requestUri))
                                                  .timeout(Duration.ofMillis(2000)).build();

        HttpResponse geocodingResponse = httpClient.send(geocodingRequest, BodyHandlers.ofString());

        return geocodingResponse.body().toString();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.