Obtain the distance between two point coordinates through the Gaode map API

       Gaode map is more detailed than Baidu map in taking the distance between two points. It can be divided into several types of APIs, providing walking, bus, and driving queries. Today we use the driving API to calculate the distance between two points. Other APIs are similar.

      Refer to the API address of Gaode Map: Path Planning-API Documentation-Development Guide-Web Service API | Gaode Map API

      Note that the keyword is: path planning.

      Here is the code that actually works.

public static double distanceCalculationSite(String start, String end) {
        BufferedReader in = null;
        //高德地图KEY
        String url = "https://restapi.amap.com/v3/direction/driving";
        String ak = "替换成你的key";
        //发型不能乱,如果参数顺序有错误,可能会得到20000的错误,参数错误
        String output = "json";
        url = url+"?origin="+start+"&destination="+end+"&extensions=all"+"&output="+output+"&key="+ak;
        try {
            URL tirc = new URL(url);
            URLConnection connection = tirc.openConnection();
            connection.setDoOutput(true);
            in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
            ObjectMapper mapper = new ObjectMapper();
            if (StringUtils.isNotEmpty(str)) {
                JsonNode jsonNode = mapper.readTree(str);
                JsonNode resultNode = jsonNode.findValue("route");
                JsonNode locationNode = resultNode.findValue("toll_distance");

                return locationNode.asDouble();
            }

        } catch (Exception e) {
            log.error("{高德地图获取两点驾驶距离}------------>"+e);
            e.printStackTrace();
        }
        return 0;
    }

Summary:
1. Amap provides a more detailed distance query API, including walking, public transportation and driving. This article uses the driving distance query API.
2. The API uses GET requests, which need to pass in parameters such as starting point and ending point coordinates, ak developer key, and output format.
3. The response returns data in JSON format, including driving distance information. JSON data needs to be parsed to obtain distance information.
4. The code example shows how to send a request, receive a response, and parse the JSON data to get the driving distance (in meters).
5. The code is implemented in Java, and related libraries such as HttpURLConnection, JSONObject, etc. need to be imported.
6. If the parameters are in the wrong order, you may get error codes such as 20000, and you need to pay attention to the correctness of the parameters.

Guess you like

Origin blog.csdn.net/heweiyabeijing/article/details/130522710