Java-通過高德地圖Api把地址轉換爲經緯度

1、高德地圖開發者註冊和登入地址 https://id.amap.com/?ref=http%3A%2F%2Flbs.amap.com%2Fdev%2Fkey
在這裏插入圖片描述
2、後端代碼

public static String getLnglat(String address) {
        //"http://restapi.amap.com/v3/geocode/geo?address=上海市東方明珠&output=JSON&key=xxxxxxxxx";
        String geturl = "http://restapi.amap.com/v3/geocode/geo?key="+YourKEY+"&address="+address;
        String location = "";
        try {
            URL url = new URL(geturl);    // 把字符串轉換爲URL請求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打開連接
            connection.connect();// 連接會話
            // 獲取輸入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循環讀取流
                sb.append(line);
            }
            br.close();// 關閉流
            connection.disconnect();// 斷開連接
            JSONObject a = JSON.parseObject(sb.toString());
            //判斷輸入的位置點是否存在
            System.out.println(sb.toString());
            if(a.getJSONArray("geocodes").size()>0)
                location=a.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
            System.out.println(location);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失敗!");
        }
        return location;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章