java中用高德工具测试两点的距离
文章讲述了如何在Java中利用DistinctUtil工具类通过高德地图API获取两个地理位置之间的驾车距离,涉及经纬度处理、URL构建、HTTP请求和JSON解析过程。
摘要由CSDN通过智能技术生成
代码如下:
String startLongitude = entity.getLONGITUDE(); // 起点(当前位置)经度
String startLatitude = entity.getLATITUDE(); // 起点纬度
String endLongitude = entity.getLO(); // 终点经度
String endLatitude = entity.getLA(); // 终点纬度
String start = startLongitude + "," + startLatitude; //进行格式拼接(当前位置/起点)
String end = endLongitude + "," + endLatitude; //进行格式拼接(目的地当前位置/终点)
String distance = DistinctUtil.getDistance(start, end); //将值给方法并调用,获取距离
建一个工具类来进行调用:
package com.qmq.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DistinctUtil {
private static final String API_KEY = "你的高德key";
private static final String BASE_URL = "https://restapi.amap.com/v3/direction/driving";
public static String getDistance(String origin, String destination) throws Exception {
// String origin = "106.6240283203125,29.656462944878474";
// String destination = "107.51576,26.305805";
System.out.println("接搜的经纬度"+origin+"目的地"+destination);
String url = BASE_URL + "?key=" + API_KEY +
"&origin=" + origin +
"&destination=" + destination +
"&output=json";
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
// 使用Fastjson解析JSON字符串
JSONObject jsonResponse = JSONObject.parseObject(response.toString());
// 获取路径信息并提取距离
JSONObject routes = jsonResponse.getJSONObject("route");
JSONArray path = routes.getJSONArray("paths");
JSONObject jsonObject = path.getJSONObject(0);
String distance = jsonObject.get("distance").toString();
double number = Double.parseDouble(distance) / 1000;
System.out.println("距离:" + number + "公里");
return Double.toString(number);
}
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_45637260/article/details/137032759