无关风月
3 天以前 70ffa97635e61caa108d3a5262c9a6d86a3eb4c5
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
package com.ruoyi.web.util;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
@Component
public class AmapApiClient {
    private static final String KEY = "e700a58329a38b2d8980790d9b1b5b06";
    private static final OkHttpClient client = new OkHttpClient();
 
    public static String getDrivingRoute(double startLat, double startLon, double endLat, double endLon) throws IOException {
        String url = "https://restapi.amap.com/v3/direction/driving?" +
                "origin=" + startLon + "," + startLat +
                "&destination=" + endLon + "," + endLat +
                "&key=" + KEY;
 
        Request request = new Request.Builder()
                .url(url)
                .build();
 
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
    public static Map<String, String> getDistance(String origins, String destination, Integer type) throws IOException {
        String url = "https://restapi.amap.com/v3/distance?key=" + KEY + "&origins=" + origins + "&destination=" + destination +
                "&type=" + type;
 
        Request request = new Request.Builder()
                .url(url)
                .build();
 
        try (Response response = client.newCall(request).execute()) {
            JSONObject jsonObject = JSON.parseObject(response.body().string());
            String status = jsonObject.getString("status");
 
//        gdInterfaceService.saveData("https://restapi.amap.com/v3/distance", "查询两点间的距离");
 
            if(status.equals("1")){
                JSONArray results = jsonObject.getJSONArray("results");
                JSONObject jsonObject1 = results.getJSONObject(0);
                Map<String, String> map = new HashMap<>();
                map.put("distance", jsonObject1.getString("distance"));//距离(米)
                map.put("duration", jsonObject1.getString("duration"));//预计时间(秒)
                return map;
            }else{
                System.err.println(jsonObject);
            }
        }
        return null;
    }
}