百度地圖通過經緯度獲取地址信息Java代碼

m8gy 9年前發布 | 7K 次閱讀 Java

地址為http://developer.baidu.com/map/webservice-geocoding.htm#.E4.BB.80.E4.B9.88.E6.98.AFGeocoding.EF.BC.9F

    逆地理編碼示例

    參數
    Latitude:
    Longitude:
    pois(是否顯示周邊100米內poi):

     (結果顯示如下)

    http://api.map.baidu.com/geocoder/v2/?ak=您的密鑰& callback=renderReverse&location=28.696117,115.958458&output=json&pois=1

    坐標:(115.95845796638,28.696117043877)對應的地址是: 江西省南昌市青山湖區創新路1號

    該點周邊100米內有10個poi

    狀態字段:

    名稱 類型 說明
    status constant 返回結果狀態值, 成功返回0,其他值請查看附錄
    location lat 緯度坐標
    lng 經度坐標
    formatted_address 結構化地址信息
    business 所在商圈信息,如 "人民大學,中關村,蘇州街"
    addressComponent city 城市名
    district 區縣名
    province 省名
    street 街道名
    street_number 街道門牌號
    pois(周邊poi數組) addr 地址信息
    cp 數據來源
    distance 離坐標點距離
    name poi名稱
    poiType poi類型,如’ 辦公大廈,商務大廈’
    point poi坐標{x,y}
    tel 電話
    uid poi唯一標識
    zip 郵編

    json示例:

    http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,116.322987&output=json&pois=1

    xml示例:

    http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,116.322987&output=xml&pois=1

    特別說明:

    1.因為Geocoding和反Geocoding使用的門址數據以及算法都不是一樣的,所以會出現不能一一對應的現象。

    2.逆地址解析location參數傳入的參數格式是(緯度lat,經度lng)。

    8.返回碼狀態表

    返回碼 定義
    0 正常
    1 服務器內部錯誤
    2 請求參數非法
    3 權限校驗失敗
    4 配額校驗失敗
    5 ak不存在或者非法
    101 服務禁用
    102 不通過白名單或者安全碼不對
    2xx 無權限
    3xx 配額錯誤
解析json
{"status":0,"result":{"location":{"lng":115.95845796638,"lat":28.696117043877},"formatted_address":"江西省南昌市青山湖區創新路1號","business":"高新開發區,火炬廣場,發展路","addressComponent":{"city":"南昌市","district":"青山湖區","province":"江西省","street":"創新路","street_number":"1號"},"cityCode":163}}

附上代碼

    package com.xuyw.wx.util;  

    import net.sf.json.JSONObject;  

    import com.xuyw.wx.config.Config;  

    /** 
     * 百度工具類 
     *  
     * @author xuyw 
     * @email xyw10000@163.com 
     * @date 2014-06-22 
     */  
    public class BaiDuUtil {  
        public static String getCity(String lat, String lng) {  
            JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result")  
                    .getJSONObject("addressComponent");  
            return obj.getString("city");  
        }  

        public static JSONObject getLocationInfo(String lat, String lng) {  
            String url = "http://api.map.baidu.com/geocoder/v2/?location=" + lat + ","  
                    + lng + "&output=json&ak=" + Config.BAIDU_GEOCONV_KEY+"&pois=0";  
            JSONObject obj = JSONObject.fromObject(HttpUtil.getRequest(url));  
            return obj;  
        }  

        public static void main(String[] args) {  
            System.out.println(BaiDuUtil.getCity("28.694439", "115.939728"));  
        }  
    }  

    package com.xuyw.wx.util;  
    import java.io.BufferedReader;  
    import java.io.DataOutputStream;  
    import java.io.IOException;  
    import java.io.InputStreamReader;  
    import java.io.UnsupportedEncodingException;  
    import java.net.HttpURLConnection;  
    import java.net.MalformedURLException;  
    import java.net.URL;  

    /** 
     * Http 簡單封裝 
     *  
     * @author xuyw 
     * @email xyw10000@163.com 
     * @date 2012-06-14 
     */  
    public class HttpUtil {  
        // 連接超時時間  
        private static final int CONNECTION_TIMEOUT = 3000;  
        //讀取超時時間  
        private static final int READ_TIMEOUT = 5000;  
        // 參數編碼  
        private static final String ENCODE_CHARSET = "utf-8";  

        /** 
         * 發送HTTP_POST請求 
         *  
         * @see 本方法默認的連接和讀取超時均為30秒 
         * @param reqURL 
         *            請求地址 
         * @param params 
         *            發送到遠程主機的正文數據[a:1,b:2] 
         * @return String 
         */  
        public static String postRequest(String reqURL, String... params) {  
            StringBuilder resultData = new StringBuilder();  
            URL url = null;  
            try {  

                url = new URL(reqURL);  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
            }  
            HttpURLConnection urlConn = null;  
            InputStreamReader in = null;  
            BufferedReader buffer = null;  
            String inputLine = null;  
            DataOutputStream out = null;  
            if (url != null) {  
                try {  
                    urlConn = (HttpURLConnection) url.openConnection();  
                    urlConn.setDoInput(true);// 設置輸入流采用字節流  
                    urlConn.setDoOutput(true);// 設置輸出流采用字節流  
                    urlConn.setRequestMethod("POST");  
                    urlConn.setUseCaches(false); // POST請求不能使用緩存  
                    urlConn.setInstanceFollowRedirects(true);  
                    urlConn.setConnectTimeout(CONNECTION_TIMEOUT);// 設置連接超時  
                    urlConn.setReadTimeout(READ_TIMEOUT); // 設置讀取超時  
                    // 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的  
                    urlConn.setRequestProperty("Content-Type",  
                            "application/x-www-form-urlencoded");  
                    urlConn.setRequestProperty("Charset", ENCODE_CHARSET);//  
                    String param = sendPostParams(params);  
                    urlConn.setRequestProperty("Content-Length",  
                            param.getBytes().length + "");//  
                    // urlConn.setRequestProperty("Connection", "Keep-Alive");  
                    // //設置長連接  
                    urlConn.connect();// 連接服務器發送消息  
                    if (!"".equals(param)) {  
                        out = new DataOutputStream(urlConn.getOutputStream());  
                        // 將要上傳的內容寫入流中  
                        out.writeBytes(param);  
                        // 刷新、關閉  
                        out.flush();  
                        out.close();  

                    }  
                    in = new InputStreamReader(urlConn.getInputStream(),  
                            HttpUtil.ENCODE_CHARSET);  
                    buffer = new BufferedReader(in);  
                    if (urlConn.getResponseCode() == 200) {  
                        while ((inputLine = buffer.readLine()) != null) {  
                            resultData.append(inputLine);  
                        }  
                    }  
                } catch (IOException e) {  
                    e.printStackTrace();  
                } finally {  
                    try {  
                        if (buffer != null) {  
                            buffer.close();  
                        }  

                        if (in != null) {  
                            in.close();  
                        }  

                        if (urlConn != null) {  
                            urlConn.disconnect();  
                        }  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
            return resultData.toString();  
        }  

        /** 
         * 發送HTTP_GET請求 
         *  
         * @see 本方法默認的連接和讀取超時均為30秒 
         * @param httpUrl 
         *            請求地址 
         * @param map 
         *            發送到遠程主機的正文數據[a:1,b:2] 
         * @return String 
         */  
        public static String getRequest(String httpUrl, String... params) {  
            StringBuilder resultData = new StringBuilder();  
            URL url = null;  
            try {  

                String paramurl = sendGetParams(httpUrl, params);  
                url = new URL(paramurl);  

            } catch (MalformedURLException e) {  
                e.printStackTrace();  
            }  
            HttpURLConnection urlConn = null;  
            InputStreamReader in = null;  
            BufferedReader buffer = null;  
            String inputLine = null;  
            if (url != null) {  
                try {  
                    urlConn = (HttpURLConnection) url.openConnection();  
                    urlConn.setRequestMethod("GET");  
                    urlConn.setConnectTimeout(CONNECTION_TIMEOUT);  
                    in = new InputStreamReader(urlConn.getInputStream(),  
                            HttpUtil.ENCODE_CHARSET);  
                    buffer = new BufferedReader(in);  
                    if (urlConn.getResponseCode() == 200) {  
                        while ((inputLine = buffer.readLine()) != null) {  
                            resultData.append(inputLine);  
                        }  
                    }  
                } catch (IOException e) {  
                    e.printStackTrace();  
                } finally {  
                    try {  
                        if (buffer != null) {  
                            buffer.close();  
                        }  

                        if (in != null) {  
                            in.close();  
                        }  

                        if (urlConn != null) {  
                            urlConn.disconnect();  
                        }  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  

            return resultData.toString();  
        }  

        /** 
         * Post追加參數 
         *  
         * @see <code>params</code> 
         * @param reqURL 
         *            請求地址 
         * @param params 
         *            發送到遠程主機的正文數據[a:1,b:2] 
         * @return 
         */  
        private static String sendPostParams(String... params) {  
            StringBuilder sbd = new StringBuilder("");  
            if (params != null && params.length > 0) {  
                for (int i = 0; i < params.length; i++) {  
                    String[] temp = params[i].split(":");  
                    sbd.append(temp[0]);  
                    sbd.append("=");  
                    sbd.append(urlEncode(temp[1]));  
                    sbd.append("&");  

                }  
                sbd.setLength(sbd.length() - 1);// 刪掉最后一個  
            }  
            return sbd.toString();  
        }  

        /** 
         * Get追加參數 
         *  
         * @see <code>params</code> 
         * @param reqURL 
         *            請求地址 
         * @param params 
         *            發送到遠程主機的正文數據[a:1,b:2] 
         * @return 
         */  
        private static String sendGetParams(String reqURL, String... params) {  
            StringBuilder sbd = new StringBuilder(reqURL);  
            if (params != null && params.length > 0) {  
                if (isexist(reqURL, "?")) {// 存在?  
                    sbd.append("&");  
                } else {  
                    sbd.append("?");  
                }  
                for (int i = 0; i < params.length; i++) {  
                    String[] temp = params[i].split(":");  
                    sbd.append(temp[0]);  
                    sbd.append("=");  
                    sbd.append(urlEncode(temp[1]));  
                    sbd.append("&");  

                }  
                sbd.setLength(sbd.length() - 1);// 刪掉最后一個  
            }  
            return sbd.toString();  
        }  

        // 查找某個字符串是否存在  
        private static boolean isexist(String str, String fstr) {  
            return str.indexOf(fstr) == -1 ? false : true;  
        }  

        /** 
         * 編碼 
         *  
         * @param source 
         * @return 
         */  
        private static String urlEncode(String source) {  
            String result = source;  
            try {  
                result = java.net.URLEncoder  
                        .encode(source, HttpUtil.ENCODE_CHARSET);  
            } catch (UnsupportedEncodingException e) {  
                e.printStackTrace();  
            }  
            return result;  
        }  
    }  

 本文由用戶 m8gy 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!