Java代码通过调用高德API获取地理位置

1.搜索高德开发平台

2.点击控制台

Java代码通过调用高德API获取地理位置_第1张图片

3.创建需要的应用和获取key

Java代码通过调用高德API获取地理位置_第2张图片

4.JAVA代码获取省份

vehicle:
  jsonFile: E:\workspace\afterend\skyable-private-cloud\cloud-device\src\main\resources\cert\shop_area.json
  autoNaviKey: 80920bdb。。。。。。。。。。
    @Value("${vehicle.autoNaviKey}")
    private String autoNaviKey;
String areaName = getProvince(latitude, longitude, autoNaviKey);
  //高德获取省份
    private static String getProvince(double latitude, double longitude, String autoNaviKey) {
        String province = "";
        try {
            // 构建请求URL
            String apiUrl = "https://restapi.amap.com/v3/geocode/regeo?key=" + autoNaviKey + "&location=" + longitude + "," + latitude;
            URL url = new URL(apiUrl);
            // 发起HTTP请求
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 获取响应数据
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                ObjectMapper objectMapper = new ObjectMapper();

                String jsonResponse = response.toString();
                JsonNode jsonNode = objectMapper.readTree(jsonResponse);
                JsonNode locationNode = jsonNode.get("regeocode");
                JsonNode node = locationNode.get("addressComponent");
                province = node.get("province").toString().replace("\"", "");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return province;
    }

你可能感兴趣的:(大数据,网络,java,开发语言)