您好,登錄后才能下訂單哦!
這篇文章主要介紹“java怎么調(diào)用百度的接口獲取起止位置的距離”,在日常操作中,相信很多人在java怎么調(diào)用百度的接口獲取起止位置的距離問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”java怎么調(diào)用百度的接口獲取起止位置的距離”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
需求:校驗(yàn)收貨地址是否超出配送范圍
重要:
做該需求的思路就是通過賣家和賣家具體的地址信息,來獲取到二者的經(jīng)緯度, 此時(shí)可以使用百度的 "地理編碼服務(wù)",即可獲取對(duì)應(yīng)的經(jīng)緯度
第二步,就是通過二者的經(jīng)緯度,按照百度接口的要求,發(fā)送,即可獲取到包含二者距離的JSON串, 此時(shí)就可以通過解析JSON獲取距離, 最后在判斷得到的距離,與自己配送的距離進(jìn)行比較,即可判斷是否超出距離
注冊(cè)一個(gè)百度賬號(hào),要求是必須實(shí)名認(rèn)證,需要填寫一些基本信息,這里需要注意一下.
首先要獲取百度地圖的一個(gè)AK
登錄百度地圖開放平臺(tái):https://lbsyun.baidu.com/
進(jìn)入控制臺(tái),創(chuàng)建應(yīng)用,獲取AK:
創(chuàng)建應(yīng)用時(shí):
類型:選服務(wù)端
IP白名單:0.0.0.0/0
對(duì)于此需求用到了兩個(gè)百度的接口, 接口地址如下:
地理編碼服務(wù): https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
https://lbsyun.baidu.com/index.php?title=webapi/directionlite-v1
代碼編寫:
1. 配置基本屬性
sky: baidumap: shop-address: 北京市西城區(qū)廣安門內(nèi)大街167號(hào)翔達(dá)大廈1層 ak: XXXXXXXXXXXXXXXXXXXXXXXXXX default-distance: 5000 // 這里在本文中沒有使用,
用于發(fā)送請(qǐng)求的工具類
說明,因?yàn)楝F(xiàn)在我們需要從服務(wù)器中發(fā)送請(qǐng)求,此時(shí)我們就需要使用HttpClient這個(gè)小框架來實(shí)現(xiàn)此功能, 下面的工具類是對(duì)此框架的一個(gè)封裝
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; /** * 發(fā)送GET方式請(qǐng)求 * * @param url * @param paramMap * @return */ public static String doGet(String url, Map<String, String> paramMap) { // 創(chuàng)建Httpclient對(duì)象 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("發(fā)送的請(qǐng)求====>{}", uri); //創(chuàng)建GET請(qǐng)求 HttpGet httpGet = new HttpGet(uri); //發(fā)送請(qǐng)求 response = httpClient.execute(httpGet); //判斷響應(yīng)狀態(tài) 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; } /** * 發(fā)送POST方式請(qǐng)求 * * @param url * @param paramMap * @return * @throws IOException */ public static String doPost(String url, Map<String, String> paramMap) throws IOException { // 創(chuàng)建Httpclient對(duì)象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 創(chuàng)建Http Post請(qǐng)求 HttpPost httpPost = new HttpPost(url); // 創(chuàng)建參數(shù)列表 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()); // 執(zhí)行http請(qǐng)求 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; } /** * 發(fā)送POST方式請(qǐng)求 * * @param url * @param paramMap * @return * @throws IOException */ public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException { // 創(chuàng)建Httpclient對(duì)象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 創(chuàng)建Http Post請(qǐng)求 HttpPost httpPost = new HttpPost(url); if (paramMap != null) { //構(gòu)造json格式數(shù)據(jù) 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"); //設(shè)置請(qǐng)求編碼 entity.setContentEncoding("utf-8"); //設(shè)置數(shù)據(jù)類型 entity.setContentType("application/json"); httpPost.setEntity(entity); } httpPost.setConfig(builderRequestConfig()); // 執(zhí)行http請(qǐng)求 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(); } }
定義一個(gè)Location類用來存放地址的經(jīng)緯度信息
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; /** * 經(jīng)度值 */ private double lng; }
自定義一個(gè)工具類,封裝對(duì)百度接口的請(qǐng)求,方便用于以后在Service層中能夠直接的調(diào)用 .
注: 因?yàn)楣ぞ吡惺亲约簩懙目赡軙?huì)有很多不合適的地方如有發(fā)現(xiàn)希望指出
另外其中有的異常類也是自定義如果沒有,改為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; /** * 獲取經(jīng)緯度 * * @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"); // 獲取經(jīng)度 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("無權(quán)限"); } } catch (Exception e) { log.info("解析JSON異常,異常信息{}", e.getMessage()); } return location; } /** * 通過兩個(gè)經(jīng)緯度信息判斷,返回距離信息 * * @return 二者的距離 */ public String getDistance(Location userLocation) { Location myShopLocation = getLocation(myShopAddress); // 起始位置, 即我的位置 String origin = myShopLocation.getLat() + "," + myShopLocation.getLng(); // 最終位置, 即終點(diǎn) String destination = userLocation.getLat() + "," + userLocation.getLng(); String url = "https://api.map.baidu.com/directionlite/v1/riding"; // 發(fā)送Get請(qǐng)求 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; } }
此時(shí)就可以通過調(diào)用工具類傳入userAddress
用戶的地址, 因?yàn)樯碳业牡刂芬呀?jīng)配置,此時(shí)就可以通過調(diào)用getDistance
方法獲取到二者的距離.
到此,關(guān)于“java怎么調(diào)用百度的接口獲取起止位置的距離”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。