这是我写的一个获取经纬度和配送距离工具类,可借鉴。(技术不够写的不够,好欢迎指点,虚心学习)
@Component
@Slf4j
public class GaoDeDistanceUtil {
//地理编码 API 服务地址
private String url1 = "https://restapi.amap.com/v3/geocode/geo";
//电动车(骑行)路线规划 API 服务地址
private String url2 = "https://restapi.amap.com/v5/direction/electrobike";
public void checkOutOfRange(String address){
//获取店铺经纬度
Map<String, String> map = new HashMap<>();
map.put("key","注册高德账号申请的Key");
map.put("address","店铺地址");
map.put("output","JSON");
map.put("city","城市");
String shopCoordinate = HttpClientUtil.doGet(url1, map);
JSONObject jsonObject = JSON.parseObject(shopCoordinate);
String info = jsonObject.getString("info");
log.info("错误原因------------>,{}",info);
if(jsonObject.getString("status").equals("0")){
throw new OrderBusinessException("店铺地址解析失败");
}
//数据解析
JSONArray addressArr = JSON.parseArray(jsonObject.get("geocodes").toString());
JSONObject c = JSON.parseObject(addressArr.get(0).toString());
String shopLocation = c.get("location").toString();
log.info("店铺经纬度坐标--------------->,{}",shopLocation);
//获取用户收货地址的经纬度坐标
map.put("address",address);
String userCoordinate = HttpClientUtil.doGet(url1, map);
jsonObject = JSON.parseObject(userCoordinate);
String info1 = jsonObject.getString("info");
log.info("错误原因------------>,{}",info1);
if(jsonObject.getString("status").equals("0")){
throw new OrderBusinessException("收货地址解析失败");
}
//数据解析
JSONArray addressArr2 = JSON.parseArray(jsonObject.get("geocodes").toString());
JSONObject c2 = JSON.parseObject(addressArr2.get(0).toString());
String userLocation = c2.get("location").toString();
log.info("客户经纬度坐标--------------->,{}",userLocation);
//电动车路线规划
Map<String, String> map1 = new HashMap<>();
map1.put("key",key);
map1.put("output","JSON");
map1.put("destination",userLocation);
map1.put("origin",shopLocation);
String json = HttpClientUtil.doGet(url2, map1);
jsonObject = JSON.parseObject(json);
String info2 = jsonObject.getString("info");
log.info("错误原因------------>,{}",info2);
if(jsonObject.getString("status").equals("0")){
throw new OrderBusinessException("配送路线规划失败");
}
//数据解析
JSONObject route = jsonObject.getJSONObject("route");
JSONArray ja = route.getJSONArray("paths");
JSONObject jobO = JSONObject.parseObject(ja.get(0).toString());
long distance = Long.parseLong(jobO.get("distance").toString());
//单位 米
log.info("配送距离--------------->,{}",distance);
if (distance > 5000){
throw new OrderBusinessException("超出配送范围");
}
}
}