1.地理编码
API服务地址:
Map map = new HashMap();
map.put("address",shopAddress);
map.put("output","json");
map.put("ak",ak);
//获取店铺的经纬度坐标
String shopCoordinate =HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//接收并解析来自 API 的响应,将其转换为 JSON 对象。
JSONObject jsonObject = JSON.parseObject(shopCoordinate);
//检查响应中的 status 字段是否为 "0"。如果不是 "0",则表示地理编码失败,抛出一个 OrderBusinessException 异常,异常信息为 "店铺地址解析失败"。
if(!jsonObject.getString("status").equals("0")){
throw new OrderBusinessException("店铺地址解析失败");
}
2.数据解析
//它从 JSON 对象中获取名为 "result" 的子对象,然后再从 "result" 对象中获取名为 "location" 的子对象。这个 "location" 对象包含了地理编码结果中的经纬度信息。
JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
//分别从 "location" 对象中获取名为 "lat" 和 "lng" 的字段值,这些字段分别代表了纬度和经度的值。
String lat = location.getString("lat");
String lng = location.getString("lng");
3.店铺经纬度坐标
String shopLngLat = lat + "," + lng;
//将收货地址添加到map中
map.put("address",address);
4.获取用户收货地址的经纬度坐标
String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
jsonObject = JSON.parseObject(userCoordinate);
if(!jsonObject.getString("status").equals("0")){
throw new OrderBusinessException("收货地址解析失败");
}
//数据解析
location = jsonObject.getJSONObject("result").getJSONObject("location");
lat = location.getString("lat");
lng = location.getString("lng");
//用户收货地址经纬度坐标
String userLngLat = lat + "," + lng;
5.驾车路线规划
API服务地址:
String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v2/driving", map);
jsonObject = JSON.parseObject(json);
if(!jsonObject.getString("status").equals("0")){
throw new OrderBusinessException("配送路线规划失败");
}
//数据解析
JSONObject result = jsonObject.getJSONObject("result");
JSONArray jsonArray = (JSONArray) result.get("routes");
Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
if(distance > 5000){
//配送距离超过5000米
throw new OrderBusinessException("超出配送范围");
}
{
"status": 0,
"message": "ok",
"result_type": "poi_type",
"results": [
{
"name": "中国工商银行24小时自助银行(北京府学路支行)",
"location": {
"lat": 40.227332,
"lng": 116.263379
},
"address": "北京市昌平区府学路福地家园7号楼07号1-2层",
"province": "北京市",
"city": "北京市",
"area": "昌平区",
"street_id": "22e11407287926b4d5b74e09",
"detail": 1,
"uid": "22e11407287926b4d5b74e09"
},
]
}