首页 > 代码库 > GoogleMapAPI

GoogleMapAPI

好多情况我们需要把一个地方的经纬度存到数据库,也就是根据地址通过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;
}