@Service
public class AddressTool {
@Autowired
private ObjectMapper mapper;
private void getLocationByAddress(String address) throws ErrorCodeException{
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=mapper.readValue(json, Map.class);
String geocodes=mapper.writeValueAsString(information.get("geocodes"));
List geocodesList=mapper.readValue(geocodes, List.class);
if(CollectionUtils.isNotEmpty(geocodesList)){
String locations=mapper.writeValueAsString(geocodesList.get(0));
Map<String,Object> location=mapper.readValue(locations, Map.class);
String [] lag=location.get("location").toString().split(",");
Location2 lo= new Location2(BigDecimal.valueOf(Float.valueOf(lag[0].trim())), BigDecimal.valueOf(Float.valueOf(lag[1].trim())));
}
}
} catch (Exception e) {
e.printStackTrace();
throw new ErrorCodeException(400,"地址反编译异常");
}finally{
try {
if(bufr!=null)bufr.close();
if(isr!=null)isr.close();
if(in!=null)in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}