puzhibing
2026-02-04 85bafa86f44fbe6646019fd8ecbab79f552ccd0a
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package com.xiaopeng.map.utils;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
 
/**
 * 高德地图步行导航工具类
 */
public class AmapWalkingRouteUtil {
    
    // 高德地图Web服务API配置
    private static final String AMAP_API_BASE_URL = "https://restapi.amap.com/v3/direction/walking";
    private static final String AMAP_GEOCODING_URL = "https://restapi.amap.com/v3/geocode/geo";
    
    // 你的高德地图API Key(请替换成你自己的)
    private final String apiKey;
    
    // HTTP客户端
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;
    
    /**
     * 构造函数
     * @param apiKey 高德地图API Key
     */
    public AmapWalkingRouteUtil(String apiKey) {
        this.apiKey = apiKey;
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }
    
    /**
     * 位置坐标类
     */
    public static class Location {
        private final double longitude; // 经度
        private final double latitude;  // 纬度
        
        public Location(double longitude, double latitude) {
            this.longitude = longitude;
            this.latitude = latitude;
        }
        
        public double getLongitude() {
            return longitude;
        }
        
        public double getLatitude() {
            return latitude;
        }
        
        @Override
        public String toString() {
            return String.format("%.6f,%.6f", longitude, latitude);
        }
    }
    
    /**
     * 步行路线结果类
     */
    public static class WalkingRouteResult {
        private int duration;      // 步行时间(秒)
        private int distance;      // 步行距离(米)
        private String origin;     // 起点地址
        private String destination; // 终点地址
        private boolean success;   // 是否成功
        private String message;    // 返回信息
        
        // getters and setters
        public int getDuration() {
            return duration;
        }
        
        public void setDuration(int duration) {
            this.duration = duration;
        }
        
        public int getDistance() {
            return distance;
        }
        
        public void setDistance(int distance) {
            this.distance = distance;
        }
        
        public String getOrigin() {
            return origin;
        }
        
        public void setOrigin(String origin) {
            this.origin = origin;
        }
        
        public String getDestination() {
            return destination;
        }
        
        public void setDestination(String destination) {
            this.destination = destination;
        }
        
        public boolean isSuccess() {
            return success;
        }
        
        public void setSuccess(boolean success) {
            this.success = success;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
        
        /**
         * 获取格式化的步行时间
         * @return 格式化的时间字符串(如:15分钟30秒)
         */
        public String getFormattedDuration() {
            int hours = duration / 3600;
            int minutes = (duration % 3600) / 60;
            int seconds = duration % 60;
 
            if (hours > 0) {
                return String.format("%d小时%d分钟", hours, minutes);
            }  else {
                return String.format("%d秒", seconds);
            }
        }
        
        /**
         * 获取格式化的步行距离
         * @return 格式化的距离字符串(如:1.2公里)
         */
        public String getFormattedDistance() {
            if (distance >= 1000) {
                double km = distance / 1000.0;
                return String.format("%.1f公里", km);
            } else {
                return String.format("%d米", distance);
            }
        }
    }
    
    /**
     * 根据地址获取经纬度坐标
     * @param address 地址信息
     * @return 经纬度坐标
     */
    public Location getLocationByAddress(String address) throws IOException {
        Map<String, String> params = new HashMap<>();
        params.put("key", apiKey);
        params.put("address", address);
        
        String url = buildUrl(AMAP_GEOCODING_URL, params);
        Request request = new Request.Builder().url(url).build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response);
            }
            
            String responseBody = response.body().string();
            JsonNode rootNode = objectMapper.readTree(responseBody);
            
            if ("1".equals(rootNode.get("status").asText())) {
                JsonNode geocodes = rootNode.get("geocodes");
                if (geocodes != null && geocodes.size() > 0) {
                    String locationStr = geocodes.get(0).get("location").asText();
                    String[] locationArray = locationStr.split(",");
                    double longitude = Double.parseDouble(locationArray[0]);
                    double latitude = Double.parseDouble(locationArray[1]);
                    return new Location(longitude, latitude);
                }
            }
            
            throw new IOException("地址解析失败: " + rootNode.get("info").asText());
        }
    }
    
    /**
     * 获取步行路线和时间
     * @param origin 起点坐标
     * @param destination 终点坐标
     * @return 步行路线结果
     */
    public WalkingRouteResult getWalkingRoute(Location origin, Location destination) {
        WalkingRouteResult result = new WalkingRouteResult();
        
        try {
            Map<String, String> params = new HashMap<>();
            params.put("key", apiKey);
            params.put("origin", origin.toString());
            params.put("destination", destination.toString());
            
            String url = buildUrl(AMAP_API_BASE_URL, params);
            Request request = new Request.Builder().url(url).build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    result.setSuccess(false);
                    result.setMessage("HTTP请求失败: " + response.code());
                    return result;
                }
                
                String responseBody = response.body().string();
                JsonNode rootNode = objectMapper.readTree(responseBody);
                
                String status = rootNode.get("status").asText();
                String info = rootNode.get("info").asText();
                
                if ("1".equals(status)) {
                    JsonNode route = rootNode.get("route");
                    JsonNode paths = route.get("paths");
                    
                    if (paths != null && paths.size() > 0) {
                        JsonNode firstPath = paths.get(0);
                        int duration = firstPath.get("duration").asInt();
                        int distance = firstPath.get("distance").asInt();
                        
                        result.setDuration(duration);
                        result.setDistance(distance);
                        result.setSuccess(true);
                        result.setMessage("成功获取步行路线");
                        
                        // 尝试获取地址信息
                        result.setOrigin(getAddressByLocation(origin));
                        result.setDestination(getAddressByLocation(destination));
                        
                    } else {
                        result.setSuccess(false);
                        result.setMessage("未找到步行路线");
                    }
                } else {
                    result.setSuccess(false);
                    result.setMessage("API返回错误: " + info);
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取步行路线失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据经纬度获取地址(逆地理编码)
     * @param location 经纬度坐标
     * @return 地址信息
     */
    private String getAddressByLocation(Location location) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("key", apiKey);
            params.put("location", location.toString());
            
            String url = buildUrl("https://restapi.amap.com/v3/geocode/regeo", params);
            Request request = new Request.Builder().url(url).build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JsonNode rootNode = objectMapper.readTree(responseBody);
                    
                    if ("1".equals(rootNode.get("status").asText())) {
                        JsonNode regeocode = rootNode.get("regeocode");
                        if (regeocode != null) {
                            return regeocode.get("formatted_address").asText();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 地址解析失败时返回坐标
        }
        return location.toString();
    }
    
    /**
     * 构建带参数的URL
     * @param baseUrl 基础URL
     * @param params 参数Map
     * @return 完整的URL
     */
    private String buildUrl(String baseUrl, Map<String, String> params) {
        StringBuilder urlBuilder = new StringBuilder(baseUrl).append("?");
        params.forEach((key, value) -> {
            urlBuilder.append(key).append("=").append(value).append("&");
        });
        // 删除最后一个&
        urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        return urlBuilder.toString();
    }
    
    /**
     * 计算两点间的直线距离(仅供参考,不是实际步行距离)
     * @param loc1 坐标1
     * @param loc2 坐标2
     * @return 直线距离(米)
     */
    public static double calculateStraightDistance(Location loc1, Location loc2) {
        double earthRadius = 6371000; // 地球半径(米)
        double lat1 = Math.toRadians(loc1.getLatitude());
        double lat2 = Math.toRadians(loc2.getLatitude());
        double deltaLat = Math.toRadians(loc2.getLatitude() - loc1.getLatitude());
        double deltaLon = Math.toRadians(loc2.getLongitude() - loc1.getLongitude());
        
        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                   Math.cos(lat1) * Math.cos(lat2) *
                   Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        
        return earthRadius * c;
    }
 
 
 
}