码迷,mamicode.com
首页 > Windows程序 > 详细

GoogleMapAPI

时间:2014-07-23 14:00:46      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:http   java   os   数据   io   for   

好多情况我们需要把一个地方的经纬度存到数据库,也就是根据地址通过GoogleMap查询出来其对应的经纬度。

public static double[] getCoordinate(String addr) {
    double[] latLng = new double[2];
    String address = null;
    try {
        address = java.net.URLEncoder.encode(addr,"utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    String url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + addr;

    URL googleMapURL = null;
    HttpURLConnection httpConn = null;
    //进行转码
    try {
       googleMapURL = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    try {
        httpConn = (HttpURLConnection)googleMapURL.openConnection(new Proxy(Proxy.Type.SOCKS,new InetSocketAddress("127.0.0.1",1080))); //这里是通过代理访问,根据自己的需要进行修改
        httpConn.setRequestMethod("GET"); //设置请求方法
        googleMapURL.openConnection().setDoOutput(true);//返回此 URLConnection 的 doOutput 标志的值
        if (httpConn != null) {
            InputStreamReader insr = new InputStreamReader(httpConn.getInputStream(),"utf-8");
            BufferedReader br = new BufferedReader(insr);
            StringBuffer sb = new StringBuffer();
            String temp;
            while ((temp = br.readLine()) != null) {
                temp = temp.trim();
                if (temp !=null && temp.length()>0) {
                    sb.append(temp);
                }
            }
            br.close();
            insr.close();

            JSONObject llInfo = new JSONObject(sb.toString());//引入org.json jar包

            String status = llInfo.getString("status");
            if ("OK".equals(status)) {
                JSONArray results = llInfo.getJSONArray("results");
                for (int i = 0; i<results.length(); i++) {
                    JSONObject llDetails = results.getJSONObject(i);

                    JSONObject loc= llDetails.getJSONObject("geometry").getJSONObject("location");

                    double y = loc.getDouble("lat");
                    double x = loc.getDouble("lng");

                    latLng[0] = x;
                    latLng[1] = y;
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("经纬度解析失败");
    }
    return latLng;
}

GoogleMapAPI,布布扣,bubuko.com

GoogleMapAPI

标签:http   java   os   数据   io   for   

原文地址:http://my.oschina.net/KingSirLee/blog/293969

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!