记录一次用高德api获取经纬度保存到数据库
高德api地址
1 .java代码(http工具是hutool)
@PostMapping("test")
@Transactional(rollbackFor = Exception.class)
public Response testResponse() {
JSONObject object;
CountyTblBean countyTblBean;
List<CountyTblBean> countyTblBeans = countyMapper.selectList(null);
for (int i = 0; i < countyTblBeans.size(); i++) {
countyTblBean = countyTblBeans.get(i);
object = new JSONObject();
object.put("address", countyTblBean.getName());
//示例说明:address 是需要获取坐标的结构化地址,output(XML)用于指定返回数据的格式,Key是用户请求数据的身份标识
object.put("key", "自己申请的key");
HttpResponse response = HttpRequest
.get("https://restapi.amap.com/v3/geocode/geo")
.form(object)
.execute();
String body = response.body();
JSONObject jsonObject = JSONObject.parseObject(body);
int status = jsonObject.getIntValue("status");
if (status == 1){
JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
try {
JSONObject jsonArrayObject = JSONObject.parseObject(jsonArray.get(0).toString());
String location = jsonArrayObject.getString("location");
String[] strings = location.split(",");
String lat = strings[0];
String lon = strings[1];
countyTblBean.setLat(Double.valueOf(lat));
countyTblBean.setLon(Double.valueOf(lon));
countyMapper.updateById(countyTblBean);
} catch (IndexOutOfBoundsException e) {
log.info("下标超出,进行下次循环");
continue;
}
}
}
return new Response().success();
}
2 .JSON 返回示例
response json 示例(默认json格式,可指定为xml)
{
"status": "1",
"info": "OK",
"infocode": "10000",
"count": "1",
"geocodes": [
"0": {
"formatted_address": "上海市静安区",
"country": "中国",
"province": "上海市",
"citycode": "021",
"city": "上海市",
"district": "静安区",
"township": [],
"neighborhood": {
…},
"building": {
…},
"adcode": "310106",
"street": [],
"number": [],
"location": "121.459384,31.247105",
"level": "区县"
}
]
}
end 欢迎大家指正
最后 如需要存储好的json文件 ,可以私聊我