/**
* Created by charlie on 15/8/7.
*/
public class BaiduGeocoder {
private static String ak = "KaK3WhH5p6ali0IM5vi9sRlk";
// 把代码中的ak值(红色字部分)更改为你自己的ak值,在百度地图API中注册一下就有。
// 调用方式:
// Map<String,String> map=BaiduGeocoder.geoCoding(“广州市");
// System.out.println("经度:"+map.get("lng")+"---纬度:"+map.get("lat"));
public static Map<String,String> geoCoding(String address){
String url = "http://api.map.baidu.com/geocoder/v2/?"
+"address=" +address
+"&output=json"
+"&ak="+ak
+"&callback=showLocation";
String json = loadJSON(url);
json = json.substring(27,json.length()-1);
JSONObject obj = JSONObject.parseObject(json);
Map<String,String> map = new HashMap<>();
if(obj.get("status").toString().equals("0")){
Double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
Double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
map.put("lng", lng.toString());
map.put("lat", lat.toString());
}else{
System.out.println("未找到相匹配的经纬度!");
}
return map;
}
// 调用方式:
// Map<String,String> map=BaiduGeocoder.reverseGeoCoding(”39.1“,“116.1”); // System.out.println("经度:"+map.get("lng")+"---纬度:"+map.get("lat")); public static Map<String, String> reverseGeoCoding(String lng, String lat) { String url = "http://api.map.baidu.com/geocoder/v2/?" + "ak=" + ak
+ "&callback=renderReverse"
+ "&location=" + lat + "," + lng
+ "&output=json&pois=1";
String json = loadJSON(url);
json = json.substring(29,json.length()-1);
JSONObject obj = JSONObject.parseObject(json);
Map<String,String> map = new HashMap<>();
if(obj.get("status").toString().equals("0")){
String address = obj.getJSONObject("result").getString("formatted_address");
String province = obj.getJSONObject("result").getJSONObject("addressComponent").getString("province");
String city = obj.getJSONObject("result").getJSONObject("addressComponent").getString("city");
map.put("address",address);
map.put("province",province);
map.put("city",city);
}else{
System.out.println("未找到匹配经纬度的地址");
}
return map;
}
public static String loadJSON (String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection urlConnection = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
System.out.println("malformed exception");
} catch (IOException e) {
System.out.println("io exception");
}
return json.toString();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/hyichao_csdn/article/details/47465861