根据地址反编译成经纬度

公司有需求将地址反编译成经纬度,前端同学做了一份,后来觉得其实后台做也可以,就在网上搜罗了一番,修改后的基础代码如下。目的是为了自己记录和大家分享。

public class AddressTool {
public static String getLocationByAddress(String address){
InputStream in =null;
InputStreamReader isr = null;
BufferedReader bufr = null;
try {
address= URLEncoder.encode(address, "utf-8");
String u="http://restapi.amap.com/v3/geocode/geo?address="+address+"&output=JSON&key=9a491a13997579f985c98165bb68d127&s=rsv3";
URL url = new URL(u);
in = url.openStream();
isr = new InputStreamReader(in);
bufr = new BufferedReader(isr);
String json;
if((json=bufr.readLine())!= null){
//转换json
Map<String,Object> information= JSON.parseObject(json, Map.class);
List geocodesList = (List)information.get("geocodes");
Map<String,Object> map = (Map)geocodesList.get(0);
String location = String.valueOf(map.get("location"));
return location;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (bufr != null) {
bufr.close();
}
if (isr != null) {
isr.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

public static void main(String[] args){
String str = "浙江省杭州市西湖区";
System.out.print(getLocationByAddress(str));
}

}

猜你喜欢

转载自www.cnblogs.com/sunnyguo/p/11864864.html