java調(diào)用百度的接口獲取起-止位置的距離
需求:校驗(yàn)收貨地址是否超出配送范圍
重要:
做該需求的思路就是通過賣家和賣家具體的地址信息,來獲取到二者的經(jīng)緯度, 此時(shí)可以使用百度的 "地理編碼服務(wù)",即可獲取對應(yīng)的經(jīng)緯度
第二步,就是通過二者的經(jīng)緯度,按照百度接口的要求,發(fā)送,即可獲取到包含二者距離的JSON串, 此時(shí)就可以通過解析JSON獲取距離, 最后在判斷得到的距離,與自己配送的距離進(jìn)行比較,即可判斷是否超出距離
注冊一個(gè)百度賬號,要求是必須實(shí)名認(rèn)證,需要填寫一些基本信息,這里需要注意一下.
首先要獲取百度地圖的一個(gè)AK
登錄百度地圖開放平臺:https://lbsyun.baidu.com/
進(jìn)入控制臺,創(chuàng)建應(yīng)用,獲取AK:


創(chuàng)建應(yīng)用時(shí):
類型:選服務(wù)端
IP白名單:0.0.0.0/0
對于此需求用到了兩個(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號翔達(dá)大廈1層
ak: XXXXXXXXXXXXXXXXXXXXXXXXXX
default-distance: 5000 // 這里在本文中沒有使用,用于發(fā)送請求的工具類
說明,因?yàn)楝F(xiàn)在我們需要從服務(wù)器中發(fā)送請求,此時(shí)我們就需要使用HttpClient這個(gè)小框架來實(shí)現(xiàn)此功能, 下面的工具類是對此框架的一個(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方式請求
*
* @param url
* @param paramMap
* @return
*/
public static String doGet(String url, Map<String, String> paramMap) {
// 創(chuàng)建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("發(fā)送的請求====>{}", uri);
//創(chuàng)建GET請求
HttpGet httpGet = new HttpGet(uri);
//發(fā)送請求
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方式請求
*
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請求
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請求
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方式請求
*
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請求
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è)置請求編碼
entity.setContentEncoding("utf-8");
//設(shè)置數(shù)據(jù)類型
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
httpPost.setConfig(builderRequestConfig());
// 執(zhí)行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();
}
}定義一個(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è)工具類,封裝對百度接口的請求,方便用于以后在Service層中能夠直接的調(diào)用 .
注: 因?yàn)楣ぞ吡惺亲约簩懙目赡軙泻芏嗖缓线m的地方如有發(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請求
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)用百度的接口獲取起-止位置的距離的文章就介紹到這了,更多相關(guān)java調(diào)用百度接口獲取起-止位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot+dubbo啟動項(xiàng)目時(shí)報(bào)錯(cuò) zookeeper not connect
這篇文章主要介紹了springboot+dubbo項(xiàng)目啟動項(xiàng)目時(shí)報(bào)錯(cuò) zookeeper not connected的問題,本文給大家定位問題及解決方案,結(jié)合實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2023-06-06
java對象和json的來回轉(zhuǎn)換知識點(diǎn)總結(jié)
在本篇文章里小編給大家分享了一篇關(guān)于java對象和json的來回轉(zhuǎn)換知識點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
關(guān)于idea中Java Web項(xiàng)目的訪問路徑問題
這篇文章主要介紹了idea中Java Web項(xiàng)目的訪問路徑問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
Ehcache簡介_動力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Ehcache簡介,使用Spring的AOP進(jìn)行整合,可以靈活的對方法的返回結(jié)果對象進(jìn)行緩存2017-07-07

