高德Web服务Api,通过地址获取经纬度

获取key:获取Key-创建工程-开发指南-Web服务 API|高德地图API (amap.com)

public static void main(String[] args) throws Exception {
        // 输入地址
        String address = "浙江省绍兴市柯桥区滨海工业区海涂九一丘";
        String utf8String = "UTF-8";
        // 构建请求 URL
        String encodedAddress = URLEncoder.encode(address, utf8String);
        System.out.println(encodedAddress);
        String url = "https://restapi.amap.com/v3/geocode/geo?key=申请的key&address=" + encodedAddress;
        System.out.println(url);
        // 发送 HTTP 请求
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");

        // 解析 JSON 响应
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }


            // 解析 JSON 响应
            JSONObject json = new JSONObject(response.toString());
            System.out.println(json);
            JSONArray geocodes = json.optJSONArray("geocodes");
            if (geocodes.length() > 0) {
                JSONObject geocode = geocodes.getJSONObject(0);
                String location = geocode.getString("location");
                String[] coordinates = location.split(",");
                System.out.println(coordinates[1]);
                System.out.println(coordinates[0]);

                double latitude = Double.parseDouble(coordinates[1]);
                double longitude = Double.parseDouble(coordinates[0]);
                System.out.println("经度:" + latitude);
                System.out.println("纬度:" + longitude);
            } else {
                System.out.println("无法获取经纬度信息");
            }
        }
    }

你可能感兴趣的:(java)