com.beyondb.geocoding.BaiduAPI.java Source code

Java tutorial

Introduction

Here is the source code for com.beyondb.geocoding.BaiduAPI.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.beyondb.geocoding;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author ZhangShuo
 */
public class BaiduAPI implements I_GeoCodeAPI {

    private static BaiduAPI baiduAPI;
    private static final String ak = "d9l3TIC7cWs7vtd88A07dro7";
    private static final String baiduURL4GeoCodingAPI = "http://api.map.baidu.com/geocoder/v2/?ak=%s&output=json&address=%s";
    private static final String baiduURL4PlaceAPI = "http://api.map.baidu.com/place/v2/search?ak=%s&scope=1&output=json&query=%s";

    public static Map<String, String> testPost(String x, String y) throws IOException {
        URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "="
                + "&callback=renderReverse&location=" + x + "," + y + "&output=json");
        URLConnection connection = url.openConnection();
        /**
         * ??URLConnection?Web
         * URLConnection???Web???
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        //        remember to clean up
        out.flush();
        out.close();
        //        ?????
        String res;
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
        StringBuilder sb = new StringBuilder("");
        while ((res = in.readLine()) != null) {
            sb.append(res.trim());
        }
        String str = sb.toString();
        System.out.println(str);
        Map<String, String> map = null;
        if (StringUtils.isNotEmpty(str)) {
            int addStart = str.indexOf("formatted_address\":");
            int addEnd = str.indexOf("\",\"business");
            if (addStart > 0 && addEnd > 0) {
                String address = str.substring(addStart + 20, addEnd);
                map = new HashMap<String, String>();
                map.put("address", address);
                return map;
            }
        }

        return null;

    }

    public static String getPointByAddress(String address, String city) throws IOException {
        String resultPoint = "";
        try {
            URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=xml&address=" + address
                    + "&" + city);

            URLConnection connection = url.openConnection();
            /**
             * ??URLConnection?Web
             * URLConnection???Web???
             */
            connection.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
            //        remember to clean up
            out.flush();
            out.close();
            //        ?????

            String res;
            InputStream l_urlStream;
            l_urlStream = connection.getInputStream();
            if (l_urlStream != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
                StringBuilder sb = new StringBuilder("");
                while ((res = in.readLine()) != null) {
                    sb.append(res.trim());
                }
                String str = sb.toString();
                System.out.println(str);
                Document doc = DocumentHelper.parseText(str); // XML
                Element rootElt = doc.getRootElement(); // ?
                //            System.out.println("" + rootElt.getName()); // ??
                Element resultElem = rootElt.element("result");
                if (resultElem.hasContent()) {
                    Element locationElem = resultElem.element("location");
                    Element latElem = locationElem.element("lat");
                    //            System.out.print("lat:"+latElem.getTextTrim()+",");
                    Element lngElem = locationElem.element("lng");
                    //            System.out.println("lng:"+lngElem.getTextTrim());
                    resultPoint = lngElem.getTextTrim() + "," + latElem.getTextTrim();
                } else {
                    System.out.println("can't compute the coor");
                    resultPoint = " , ";
                }
            } else {
                resultPoint = " , ";
            }

        } catch (DocumentException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        }
        return resultPoint;
    }

    /**
     * ????
     * ???? key lng(?),lat()
     * @param address
     * @param city
     * @return 
     */
    public static Map<String, String> getLongLatCoordinate(String address, String city) {
        Map<String, String> map = new HashMap<>();
        try {
            //   ???utf-816 
            address = URLEncoder.encode(address, "UTF-8");
            //   ????? 
            //  System.setProperty("http.proxyHost","192.168.172.23"); 
            //  System.setProperty("http.proxyPort","3209"); 
            URL resjson = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=json&address="
                    + address + "&" + city);

            BufferedReader in = new BufferedReader(new InputStreamReader(resjson.openStream()));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            in.close();
            String str = sb.toString();
            System.out.println("return json:" + str);
            if (str.contains("lng")) {
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
                    String lng = str.substring(lngStart + 5, lngEnd);
                    String lat = str.substring(lngEnd + 7, latEnd);
                    map.put("lng", lng);
                    map.put("lat", lat);
                }
            } else {
                map.put("lng", " ");
                map.put("lat", " ");
                Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING,
                        "Parse coordinate from " + str + " is empty!");
                System.out.println("lng,lat is empty!" + str + "--" + map.get("lng") + "," + map.get("lat"));
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        }
        return map;
    }

    public static void main(String[] args) throws IOException {
        //       Map<String, String> json = BaiduAPI.testPost("29.542938", "114.064022");
        //        System.out.println("address :" + json.get("address"));
        //        String str = BaiduAPI.getPointByAddress("??2400????", "");
        //        System.out.println(str);
        //        Map<String, String> map = BaiduAPI.getLongLatCoordinate("?310????","");
        //        if (null != map) {
        //            System.out.println(map.get("lng"));
        //            System.out.println(map.get("lat"));
        //        }

        //Coordinate coord =BaiduAPI.getInstance().getCoordinate("?310????","");
        Coordinate coord = BaiduAPI.getInstance().getCoordinate(
                "?310????", "");
        if (null != coord) {
            System.out.println("lat:" + coord.Latitude);
            System.out.println("lng:" + coord.Longitude);
        }
        Map<String, Coordinate> places = BaiduAPI.getInstance().getPlaces("?", "");
        if (places != null) {
            for (Map.Entry<String, Coordinate> entry : places.entrySet()) {
                String placeName = entry.getKey();
                Coordinate coordinate = entry.getValue();
                System.out.println("placeName:" + placeName);
                System.out.println("lat:" + coordinate.Latitude);
                System.out.println("lng:" + coordinate.Longitude);
            }
        }
    }

    public static synchronized BaiduAPI getInstance() {
        if (baiduAPI == null) {
            baiduAPI = new BaiduAPI();
        }
        return baiduAPI;
    }

    @Override
    public Coordinate getCoordinate(String address, String city) {
        Coordinate coord = null;

        try {
            if (address == null || address.trim().length() == 0) {

                Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, "?? !");
                return null;
            }

            //   address?
            //????? UTF-8 ??
            String encodeAddress = URLEncoder.encode(address, "UTF-8");

            //city = URLEncoder.encode(city, "UTF-8");

            String queryUrl = "";
            if (city.isEmpty()) {
                queryUrl = String.format(baiduURL4GeoCodingAPI, ak, encodeAddress);
            } else {
                String citybaiduURL4GeoCodingAPI = baiduURL4GeoCodingAPI + "&city=%s";
                queryUrl = String.format(citybaiduURL4GeoCodingAPI, ak, encodeAddress, city);
            }
            URL query = new URL(queryUrl);

            HttpURLConnection connection = (HttpURLConnection) query.openConnection();
            //?
            InputStream in = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));//?
            ;
            String line;
            StringBuilder sb = new StringBuilder("");
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line.trim());
            }
            in.close();

            String output = sb.toString();
            //            System.out.println("return json:" + output);     
            if (output == null || output.isEmpty()) {
                Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING,
                        "" + address + "??");
                return null;
            }
            //?json
            //?
            //?
            //{
            //   status: 0,
            //   result: 
            //   {
            //   location: 
            //{
            //lng: 116.30814954222,
            //lat: 40.056885091681
            //},
            //precise: 1,
            //confidence: 80,
            //level: ""
            //}
            //}
            //}
            JSONObject jsonObj = JSONObject.fromObject(output);

            int status = jsonObj.getInt("status");
            if (status == 0) {
                //??

                JSONObject result = jsonObj.getJSONObject("result");

                if (result.isEmpty()) {
                    String msg = jsonObj.getString("msg");
                    Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING, "\u67e5\u8be2{0} {1}",
                            new Object[] { address, msg });
                    return null;
                }
                double lng = result.getJSONObject("location").getDouble("lng");
                double lat = result.getJSONObject("location").getDouble("lat");

                coord = new Coordinate();
                coord.Latitude = lat;
                coord.Longitude = lng;
            } else {
                String msg = jsonObj.getString("msg");
                Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING, "\u67e5\u8be2{0} {1}",
                        new Object[] { address, msg });
                Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING,
                        "?????\n"
                                + "A:??\n"
                                + "B:city??\n"
                                + "C:??????");
                return null;
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

        return coord;

    }

    /**
     * ??????
     *???????
     * @param address
     * @param city
     * @return
     */
    public Map<String, Coordinate> getPlaces(String address, String city) {
        Map<String, Coordinate> map = null;
        try {
            if (address == null || address.trim().length() == 0) {

                Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, "?? !");
                return null;
            }

            // address?
            //????? UTF-8 ??
            String encodeAddress = URLEncoder.encode(address, "UTF-8");
            String encodeCity = URLEncoder.encode(city == null ? "" : city, "UTF-8");

            String queryUrl = "";
            if (city == null || city.isEmpty()) {
                queryUrl = String.format(baiduURL4PlaceAPI, ak, encodeAddress);
            } else {
                String region_baiduURL4PlaceAPI = baiduURL4PlaceAPI + "&region=%s";
                queryUrl = String.format(region_baiduURL4PlaceAPI, ak, encodeAddress, encodeCity);
            }
            URL query = new URL(queryUrl);

            HttpURLConnection connection = (HttpURLConnection) query.openConnection();
            //?
            InputStream in = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));//?

            String line;
            StringBuilder sb = new StringBuilder("");
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line.trim());
            }
            in.close();

            String output = sb.toString();
            //System.out.println("return json:" + output);   
            String info = "" + address + "??";
            if (output == null || output.isEmpty()) {
                Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING, info);
                return null;
            }
            //        ?
            //??        
            //status    Int    API??0
            //message    string    API??"ok"
            //total    int    page_num?total
            JSONObject jsonObj = JSONObject.fromObject(output);

            int status = jsonObj.getInt("status");

            if (status == 0) {
                //??

                JSONArray results = jsonObj.getJSONArray("results");

                for (int i = 0; i < results.size(); i++) {
                    if (map == null) {
                        map = new HashMap<>();
                    }
                    JSONObject obj = results.getJSONObject(i);
                    String name = obj.getString("name");
                    String add = obj.getString("address");
                    double lng = obj.getJSONObject("location").getDouble("lng");
                    double lat = obj.getJSONObject("location").getDouble("lat");
                    Coordinate coord = new Coordinate();
                    coord.Latitude = lat;
                    coord.Longitude = lng;

                    map.put(name + " " + add, coord);
                }
                //
                //  {
                //         name : "",
                //         location : 
                //         {
                //            lat : 39.901442,
                //            lng : 116.392169
                //         },
                //         address : "?114?",
                //         street_id : "881a28e7ba81f35ef942b248",
                //         telephone : "(010)63033091",
                //         uid : "881a28e7ba81f35ef942b248"
                //      },
                //           

            } else {
                String msg = jsonObj.getString("message");
                Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING, "\u67e5\u8be2{0} {1}",
                        new Object[] { address, msg });

                return null;
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

        return map;
    }

    @Override
    public String getApiType() {
        return this.getClass().getName();
    }
}