Java後臺調用百度地圖接口實現通過經緯度查詢地址

package free.system.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;


public class BaiduMapUtils {
    /**
     * 百度地圖通過經緯度來獲取地址,傳入參數緯度lat、經度lng
     * @param lat
     * @param lng
     * @return
     */
    public static String getAddress(String lat, String lng) throws IOException {
        JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result");
        System.out.println(obj);
        return obj.getString("formatted_address");
    }

    public static JSONObject getLocationInfo(String lat, String lng) throws IOException {
        String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=你的ak&output=json&coordtype=wgs84ll&location="+lat+","+lng;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String line;
        String res = "";
        while((line = in.readLine())!= null) {
            res += line+"\n";
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(res);
        return jsonObject;
    }


    public static void main(String[] args) throws IOException {
        String address = getAddress("30.2084","120.21201");
        System.out.println(address);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章