首页 > 代码库 > 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。