Home  >  Article  >  Java  >  How to use Java to call Baidu interface to get the distance between two locations?

How to use Java to call Baidu interface to get the distance between two locations?

王林
王林forward
2023-05-07 23:22:061726browse

Requirement: Verify whether the delivery address is outside the delivery range

Important:
The idea of ​​​​making this requirement is to obtain the longitude and latitude of the seller and the seller through their specific address information. At this time You can use Baidu's "Geocoding Service" to obtain the corresponding longitude and latitude
The second step is to send the longitude and latitude of the two according to the requirements of the Baidu interface, and you can obtain a JSON string containing the distance between the two. At this time, you can obtain the distance by parsing JSON, and finally compare the obtained distance with your own delivery distance to determine whether the distance is exceeded.

Register a Baidu account, which requires real-name authentication and needs to be filled in Some basic information needs to be paid attention to here.

First of all, you need to obtain an AK from Baidu Map

Log in to the Baidu Map open platform: https://lbsyun.baidu.com/

Enter the console, create an application, and obtain the AK:

How to use Java to call Baidu interface to get the distance between two locations?

How to use Java to call Baidu interface to get the distance between two locations?

##When creating an application:

Type: Select server
IP whitelist: 0.0.0.0/0

Two Baidu interfaces are used for this requirement. The interface addresses are as follows:

Geocoding service: https:// lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

https://lbsyun.baidu.com/index.php?title=webapi/directionlite-v1

Code writing:

1. Configure basic properties

sky:
  baidumap:
    shop-address: 北京市西城区广安门内大街167号翔达大厦1层
    ak: XXXXXXXXXXXXXXXXXXXXXXXXXX
    default-distance: 5000   // 这里在本文中没有使用,

Tool class for sending requests

Explanation, because now we need to send requests from the server ,At this time we need to use the small framework of HttpClient to implement this function. The following tool class is an encapsulation of this framework

package com.sky.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Http工具类
 */
@Slf4j
public class HttpClientUtil {
    static final int TIMEOUT_MSEC = 5 * 1000;
    /**
     * 发送GET方式请求
     *
     * @param url
     * @param paramMap
     * @return
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();
            log.info("发送的请求====>{}", uri);
            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);
            //发送请求
            response = httpClient.execute(httpGet);
            //判断响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 发送POST方式请求
     *
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     * 发送POST方式请求
     *
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (paramMap != null) {
                //构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
                //设置请求编码
                entity.setContentEncoding("utf-8");
                //设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }
}
Define a Location class to store the longitude and latitude information of the address

package com.sky.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * @author : Cookie
 * date : 2023/4/20 9:20
 * explain :
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Location {
    /**
     * 纬度值
     */
    private double lat;
    /**
     * 经度值
     */
    private double lng;
}

Customize a tool class to encapsulate the request to the Baidu interface, so that it can be directly called in the Service layer in the future.

Note: Because the toolbar is written by yourself, it is possible There will be many inappropriate places. If you find any, please point them out.

In addition, some of the exception classes are also customized. If not, just change it to RuntimeException.

package com.sky.utils;
import com.sky.entity.Location;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import java.util.HashMap;
/**
 * @author : Cookie
 * date : 2023/4/19 23:10
 * explain :
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@Slf4j
public class BaiduMapUtil {
    // 获取配置类中的值
    @Value("${sky.baidumap.shop-address}")
    private String myShopAddress;
    @Value("${sky.baidumap.ak}")
    private String ak;
    /**
     * 获取经纬度
     *
     * @param userAddress
     * @return
     */
    public Location getLocation(String userAddress) {
        String URL = "https://api.map.baidu.com/geocoding/v3";
        HashMap<String, String> map = new HashMap<>();
        map.put("address", userAddress);
        map.put("output", "json");
        map.put("ak", ak);
        String body = HttpClientUtil.doGet(URL, map);
        Location location = new Location();
        try {
            JSONObject jsonObject = new JSONObject(body);
//           获取Status
            String status = jsonObject.getString("status");
            if ("0".equals(status)) {
//            解析JSON
                JSONObject res = jsonObject.getJSONObject("result").getJSONObject("location");
//            获取经度
                String lng = res.getString("lng");
                Double transferLnf = Double.parseDouble(lng);
                location.setLng(transferLnf);
//            获取纬度
                String lat = res.getString("lat");
                Double transferLat = Double.parseDouble(lat);
                location.setLat(transferLat);
            } else {
//                如果没有返回排除异常交给全局异常处理
                throw new RuntimeException("无权限");
            }
        } catch (Exception e) {
            log.info("解析JSON异常,异常信息{}", e.getMessage());
        }
        return location;
    }
    /**
     * 通过两个经纬度信息判断,返回距离信息
     *
     * @return 二者的距离
     */
    public String getDistance(Location userLocation) {
        Location myShopLocation = getLocation(myShopAddress);
//        起始位置, 即我的位置
        String origin = myShopLocation.getLat() + "," + myShopLocation.getLng();
//        最终位置, 即终点
        String destination = userLocation.getLat() + "," + userLocation.getLng();
        String url = "https://api.map.baidu.com/directionlite/v1/riding";
//        发送Get请求
        HashMap<String, String> map = new HashMap<>();
        map.put("origin", origin);
        map.put("destination", destination);
        map.put("ak", ak);
        map.put("steps_info", "0");
        String result = HttpClientUtil.doGet(url, map);
        String distance = null;
        try {
            JSONObject jsonObject = new JSONObject(result);
            distance = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0).getString("distance");
        } catch (JSONException e) {
            log.info("路径异常");
        }
        log.info("二者距离{}", distance);
        return distance;
    }
}
You can pass it at this time Call the tool class to pass in the

userAddress user's address. Since the merchant's address has been configured, you can get the distance between the two by calling the getDistance method.

The above is the detailed content of How to use Java to call Baidu interface to get the distance between two locations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete