代码如下:
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);}}