package com.matrix.system.shopXcx.api.tools; import java.io.IOException; import java.net.URL; import com.matrix.core.tools.LogUtil; import com.matrix.system.shopXcx.api.pojo.AddressUntilsPOJO; import net.sf.json.JSONObject; /** * @author wlz * 根据经纬度获取省市区 * 通过百度地图API */ public class AddressUntils { /** * 根据经纬度查询 * @param log * @param lat * @return */ public static AddressUntilsPOJO getAdd(String log, String lat ){ //lat 小 log 大 //参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项) String urlString = "http://api.map.baidu.com/geocoder/v2/?ak=byxpjOG965GXUYDnBlCNvYaBxOu2FsMv&callback=renderReverse&location="+ lat + "," + log + "&output=json&pois=1"; String res = ""; try { URL url = new URL(urlString); java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { res += line+"\n"; } in.close(); } catch (Exception e) { System.out.println("error in wapaction,and e is " + e.getMessage()); LogUtil.error("根据经纬度获取省市区异常", e); } System.out.println(res); LogUtil.info("根据经纬度获取省市区res。。。"+res); String ns= res.substring(res.indexOf("{"),res.lastIndexOf("}")+1); LogUtil.info("根据经纬度获取省市区截取json。。。"+ ns); JSONObject jsonObject = JSONObject.fromObject(ns); JSONObject jsonObj = JSONObject.fromObject(jsonObject.getString("result")); JSONObject jsonData = jsonObj.getJSONObject("addressComponent"); LogUtil.info("根据经纬度获取省市区jsonData。。。"+ jsonData); AddressUntilsPOJO address = new AddressUntilsPOJO(); address.setProvince(jsonData.get("province").toString()); address.setCity(jsonData.get("city").toString()); address.setDistrict(jsonData.get("district").toString()); LogUtil.info("根据经纬度获取省市区AddressUntilsPOJO。。。"+ address); return address; } public static void main(String[] args) throws IOException { AddressUntilsPOJO address = getAdd("113.095505", "28.260786"); System.out.println(address); } }