1、進入百度地圖開發平臺

2、編寫java代碼,調用百度的API
一、根據不規則的地址信息獲取對應的"緯度,經度"
/**
* 根據詳細地址獲取經緯度
* @param addr
* @return
* @throws IOException
*/
private static String getGeocoderLatitude(String address) throws IOException{
//緯度
String lat = "";
//經度
String lng = "";
String addr = URLEncoder.encode(address, "UTF-8");
URL url = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + addr + "&output=json&ak=" + bdMapAK);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String res;
StringBuilder sb = new StringBuilder();
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
//System.out.println(sb.toString());
JSONObject jsonData = JSONObject.fromObject(sb.toString());
JSONObject result = (JSONObject) jsonData.get("result");
JSONObject location = (JSONObject) result.get("location");
if(null != location.get("lng") && null != location.get("lat")){
lat = location.get("lat").toString();
lng = location.get("lng").toString();
}
return lat + "," + lng;
}
二、根據經緯度獲取當前地址的行政區劃信息
/**
* 根據經緯度座標解析地址詳情
* @param LatitudeAndLongitude
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static String getposition(String LatitudeAndLongitude)
throws UnsupportedEncodingException, IOException {
BufferedReader in = null;
URL url = new URL("http://api.map.baidu.com/geocoder/v2/?location=" + LatitudeAndLongitude + "&output=json&ak="
+ bdMapAK);
in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String res;
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
//System.out.println(sb.toString());
JSONObject jsonData = JSONObject.fromObject(sb.toString());
JSONObject result = (JSONObject) jsonData.get("result");
JSONObject addressComponent = (JSONObject) result.get("addressComponent");
System.out.println("省:" + addressComponent.get("province").toString());
System.out.println("市:" + addressComponent.get("city").toString());
System.out.println("區:" + addressComponent.get("district").toString());
System.out.println("省-編碼:"+ getPAdCode(addressComponent.get("adcode").toString()));
System.out.println("市-編碼:"+ getCAdCode(addressComponent.get("adcode").toString()));
System.out.println("區-編碼:"+ addressComponent.get("adcode").toString());
return "";
}
三、運行結果示例
public static void getAddrCode(String address) throws IOException{
String str = getGeocoderLatitude(address);
getposition(str);
}
public static void main(String[] args) {
try {
Test2.getAddrCode("天安門");
} catch (IOException e) {
e.printStackTrace();
}
}
