Java调用高德地图API根据详细地址获取经纬度

步骤一:注册高德开发者账号并创建应用

  1. 访问高德开放平台https://lbs.amap.com/

  2. 登录后,在控制台中创建一个应用,获取生成的应用key。这个key将用于访问高德地图API。

步骤二:使用Java发送HTTP请求获取经纬度

您可以使用Java中的HttpURLConnectionHttpClient等工具发送HTTP请求到高德地图API,并传递参数以获取经纬度信息。以下是一个使用HttpURLConnection的示例代码:

package com.lps.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class AMapAPI {
    private static final String API_URL = "https://restapi.amap.com/v3/geocode/geo";
    private static final String KEY = "你的key 横扫饥饿做回自己";

    public static void main(String[] args) {

        String address = "润州区牌湾派出所";
        String city = "镇江市";
        String url = API_URL + "?key=" + KEY + "&address=" + address + "&city=" + city;
        try {
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            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();
                JSONObject json = JSONObject.parseObject(response.toString());
                String status = json.getString("status");
                if (status.equals("1")) {
                    JSONObject geocode = json.getJSONArray("geocodes").getJSONObject(0);
                    String location = geocode.getString("location");
                    System.out.println(address+"经纬度:" + location);
                } else {
                    System.out.println("查询失败:" + json.getString("info"));
                }
            } else {
                System.out.println("HTTP请求失败:" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

步骤三:解析API返回的JSON数据

使用JSONObject类解析API返回的JSON数据,从中提取经纬度信息。确保您在代码中替换YOUR_APP_KEY为您实际的应用key。

以上代码将帮助您调用高德地图API获取详细地址的经纬度信息,以便在您的应用程序中使用。记得处理可能出现的异常情况,例如网络连接问题或无法解析的JSON数据。

猜你喜欢

转载自blog.csdn.net/lps12345666/article/details/132437401