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


創(chuàng)建應用時:
類型:選服務端
IP白名單:0.0.0.0/0
對于此需求用到了兩個百度的接口, 接口地址如下:
地理編碼服務: 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ū)廣安門內大街167號翔達大廈1層
ak: XXXXXXXXXXXXXXXXXXXXXXXXXX
default-distance: 5000 // 這里在本文中沒有使用,用于發(fā)送請求的工具類
說明,因為現(xiàn)在我們需要從服務器中發(fā)送請求,此時我們就需要使用HttpClient這個小框架來實現(xiàn)此功能, 下面的工具類是對此框架的一個封裝
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);
//判斷響應狀態(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) {
//構造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");
//設置請求編碼
entity.setContentEncoding("utf-8");
//設置數(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();
}
}定義一個Location類用來存放地址的經緯度信息
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;
}自定義一個工具類,封裝對百度接口的請求,方便用于以后在Service層中能夠直接的調用 .
注: 因為工具列是自己寫的可能會有很多不合適的地方如有發(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;
/**
* 獲取經緯度
*
* @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";
// 發(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;
}
}此時就可以通過調用工具類傳入userAddress用戶的地址, 因為商家的地址已經配置,此時就可以通過調用getDistance方法獲取到二者的距離.
到此這篇關于java調用百度的接口獲取起-止位置的距離的文章就介紹到這了,更多相關java調用百度接口獲取起-止位置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot+dubbo啟動項目時報錯 zookeeper not connect
這篇文章主要介紹了springboot+dubbo項目啟動項目時報錯 zookeeper not connected的問題,本文給大家定位問題及解決方案,結合實例代碼給大家講解的非常詳細,需要的朋友可以參考下2023-06-06

