比较简单,只需要在百度注册AK(key)就可以使用
可以用百度提供的SearchHttpAK,但用HttpClient更好,更通用。
实例代码如下
String url="https://api.map.baidu.com/geocoding/v3";
String url1="https://api.map.baidu.com/directionlite/v1/driving";
//商家经纬
Map map=new HashMap<>();
map.put("address",shop_address);
map.put("output","json");
map.put("ak",ak);
String s = HttpClientUtil.doGet(url, map);
//alibaba的fastjson
JSONObject jsonObject = JSONObject.parseObject(s);
//todo 将JSONObject变为double
if (!jsonObject.getString("status").equals("0") ) {
throw new OrderBusinessException("商家经纬获取失败");
}
JSONObject jsonObject1 = jsonObject.getJSONObject("result").getJSONObject("location");
String lng = jsonObject1.getString("lng").substring(0,9);
String lat = jsonObject1.getString("lat").substring(0,9);
String shoplnglat=lat+","+lng;//用户经纬
map.put("address",address);
String s1 = HttpClientUtil.doGet(url, map);
JSONObject jsonObject2 = JSONObject.parseObject(s1);
if (!jsonObject2.getString("status").equals("0") ) {
throw new OrderBusinessException("用户经纬获取失败");
}
JSONObject jsonObject3 = jsonObject2.getJSONObject("result").getJSONObject("location");
String lng1 = jsonObject3.getString("lng").substring(0,9);
String lat1 = jsonObject3.getString("lat").substring(0,9);
String userlnglat=lat1+","+lng1;
//轻量级路程查距离
Map map1=new HashMap<>();
map1.put("steps_info","0");
map1.put("origin",shoplnglat);
map1.put("destination",userlnglat);
map1.put("ak",ak);
String s2 = HttpClientUtil.doGet(url1, map1);
JSONObject jsonObject4 = JSONObject.parseObject(s2);
if(!jsonObject4.getString("status").equals("0")){
throw new OrderBusinessException("距离获取失败");
}
JSONArray jsonArray = jsonObject4.getJSONObject("result").getJSONArray("routes");
//todo jsonArray.get(0).toString();
JSONObject jsonObject5 = jsonArray.getJSONObject(0);
String string = jsonObject5.getString("distance");
double distance = Double.parseDouble(string);
log.info("distance:{}",distance);
if(distance>10000.0){
throw new OrderBusinessException("超出配送范围");
}
}