1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.utils.HttpClientUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.LinkedHashMap;
import java.util.Map;
@SpringBootTest
public class BaiduMapTest {
public static String AK = "输入自己的AK";
@Test
public void DemoTest() throws Exception {
String locationOri = getLocation("上海静安嘉里中心-南区商场", AK);
String locationDes = getLocation("上海市浦东新区上海图书馆", AK);
int distance = getDistance(locationOri, locationDes, AK);
System.out.println(distance);
}
/**
* 获取经纬度,返回格式:纬度,经度
* @param address
* @param ak
* @return
* @throws Exception
*/
private String getLocation(String address, String ak) throws Exception {
String url = "https://api.map.baidu.com/geocoding/v3/?";
// 创建请求参数
Map params = new LinkedHashMap<String, String>();
params.put("address", address);
params.put("output", "json");
params.put("ak", ak);
// 发送GET请求
String jsonStr = HttpClientUtil.doGet(url, params);
// 创建ObjectMapper实例
ObjectMapper objectMapper = new ObjectMapper();
// 解析JSON字符串为JsonNode对象
JsonNode rootNode = objectMapper.readTree(jsonStr);
// 逐层获取节点
// 判断访问状态是否成功
int status = rootNode.get("status").asInt();
if (status != 0) {
throw new OrderBusinessException(MessageConstant.ADDRESS_PARSING_FAILED);
}
JsonNode resultNode = rootNode.get("result");
JsonNode locationNode = resultNode.get("location");
// 获取lng和lat的值
double lat = locationNode.get("lat").asDouble();
double lng = locationNode.get("lng").asDouble();
return lat + "," + lng;
}
/**
* 获取距离
* @param origin
* @param destination
* @param ak
* @return
* @throws Exception
*/
private int getDistance(String origin, String destination, String ak) throws Exception {
String url = "https://api.map.baidu.com/directionlite/v1/riding?";
// 创建请求参数
Map params = new LinkedHashMap<String, String>();
params.put("origin", origin);
params.put("destination", destination);
params.put("output", "json");
params.put("ak", ak);
// 发送请求
String jsonStr = HttpClientUtil.doGet(url, params);
// 创建ObjectMapper实例
ObjectMapper objectMapper = new ObjectMapper();
// 解析JSON字符串为JsonNode对象
JsonNode rootNode = objectMapper.readTree(jsonStr);
// 逐层获取节点
// 判断访问状态是否成功
int status = rootNode.get("status").asInt();
if (status != 0) {
throw new OrderBusinessException(MessageConstant.ADDRESS_PARSING_FAILED);
}
// 获取距离
JsonNode resultNode = rootNode.get("result");
JsonNode routesNode = resultNode.get("routes");
String distance = routesNode.get(0).get("distance").toString();
return Integer.parseInt(distance);
}
}
|