高德地图服务端对接APIUtil
生活随笔
收集整理的這篇文章主要介紹了
高德地图服务端对接APIUtil
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
高德地圖開發文檔入口
info
Util
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.winsky.carhailing.common.util.PageUtil; import com.winsky.carhailing.common.util.amap.enums.AMapAPIAddress; import com.winsky.carhailing.common.util.amap.enums.AMapAPIDevAccountInfo; import com.winsky.carhailing.common.util.amap.model.bo.AmapBatchBO; import com.winsky.carhailing.common.util.amap.model.bo.AmapResPathData; import com.winsky.carhailing.common.util.amap.model.bo.AmapResTrackingData; import com.winsky.carhailing.common.util.amap.model.res.ReGeoRes; import com.winsky.carhailing.common.util.amap.model.res.TrackTraceSearchRes; import com.winsky.carhailing.common.util.amap.model.res.WeatherInfoRes; import com.winsky.carhailing.common.util.gps.CoordinateConversionUtil; import com.winsky.carhailing.common.util.gps.GPSPoint; import com.winsky.carhailing.common.util.httpClient.HttpClientUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.math.BigDecimal; import java.util.*;/*** 高德API https://lbs.amap.com/api/webservice/guide/api/direction* @date create in*/ public class AmapApi {private static final Logger logger = LoggerFactory.getLogger(AmapApi.class);/*** 獲取駕車規劃 -- 起點與終點的駕車規劃*/public static AmapResPathData getDriverNavPathData(GPSPoint startPoint, GPSPoint endPoint) {AmapResPathData amapResPathData = new AmapResPathData();try {Map filter = new HashMap();//起始經緯度filter.put("origin", startPoint.getLng() + "," + startPoint.getLat());filter.put("destination", endPoint.getLng() + "," + endPoint.getLat());//駕車選擇策略 2:距離優先,不考慮路況,僅走距離最短的路線,但是可能存在穿越小路/小區的情況filter.put("strategy", "2");//返回結果控制 base:返回基本信息;all:返回全部信息filter.put("extensions", "base");//返回數據格式類型 可選值:JSON,XMLfilter.put("output", "JSON");//高德用戶唯一標識 用戶在高德地圖官網申請filter.put("key", AMapAPIDevAccountInfo.KEY.value);//https://lbs.amap.com/api/webservice/guide/api/direction 駕車路徑規劃接口String response = HttpClientUtil.getInstance().sendHttpPost(AMapAPIAddress.DRIVER_NAV_API_URL.ADDRESS, filter);//高德放回的jsonJSONObject jb = JSON.parseObject(response);//結果狀態值,0:請求失敗;1:請求成功if (jb.getIntValue("status") == 1) {//route 駕車路徑規劃信息列表if (null != jb && jb.getJSONObject("route") != null) {//paths 駕車換乘方案 distance :行駛距離 單位:米; duration : 預計行駛時間 單位:秒amapResPathData = jb.getJSONObject("route").getJSONArray("paths").getJSONObject(0).toJavaObject(AmapResPathData.class);} else {amapResPathData.setDistance(0L);amapResPathData.setDuration(0L);}} else {logger.error("高德接口請求失敗:{}", response);}} catch (Exception e) {logger.error("獲取駕車規劃", e);}return amapResPathData;}/*** 獲取拼車訂單原始駕車規劃* 訂單的起點終點,剩余進行中行程的未接到的起點和未送到的目的地,與訂單起點直線距離排序,在起點終點距離范圍內的是途經點*/public static AmapResPathData getDriverNavPathData(GPSPoint startPoint, GPSPoint endPoint, List<GPSPoint> waypoints) {AmapResPathData amapResPathData = new AmapResPathData();try {Map filter = new HashMap();filter.put("origin", startPoint.getLng() + "," + startPoint.getLat());filter.put("extensions", "base");filter.put("output", "JSON");//排序gpsPointsSort(startPoint, waypoints);StringBuilder waypointsVal = new StringBuilder();StringBuilder endpointVal = new StringBuilder();Iterator<GPSPoint> itr = waypoints.iterator();Double distance = CoordinateConversionUtil.getDistance(startPoint.getLng(), startPoint.getLat(), endPoint.getLng(), endPoint.getLat());while (itr.hasNext()) {GPSPoint point = itr.next();//重復的點去除if(startPoint.equals(point)){continue;}//按距離排序,途經點算到訂單重點為止if(endPoint.equals(point)){break;}//超出起點終點距離范圍內的去除 // if(distance<CoordinateConversionUtil.getDistance(startPoint.getLng(),startPoint.getLat(),point.getLng(),point.getLat()) // || distance<CoordinateConversionUtil.getDistance(endPoint.getLng(),endPoint.getLat(),point.getLng(),point.getLat())){ // continue; // }if(itr.hasNext()){waypointsVal.append(point.getLng() + "," + point.getLat()).append(";");} else {endpointVal.append(point.getLng() + "," + point.getLat());}}filter.put("waypoints", waypointsVal.toString());filter.put("destination", endPoint.getLng() + "," + endPoint.getLat());filter.put("key", AMapAPIDevAccountInfo.KEY.value);String response = HttpClientUtil.getInstance().sendHttpPost(AMapAPIAddress.DRIVER_NAV_API_URL.ADDRESS, filter);JSONObject jb = JSON.parseObject(response);if (jb.getIntValue("status") == 1) {if (null != jb && jb.getJSONObject("route") != null) {amapResPathData = jb.getJSONObject("route").getJSONArray("paths").getJSONObject(0).toJavaObject(AmapResPathData.class);} else {amapResPathData.setDistance(0L);amapResPathData.setDuration(0L);}} else {logger.error("高德接口請求失敗:{}", response);}} catch (Exception e) {logger.error("獲取駕車規劃", e);}return amapResPathData;}/*** 與起點直線距離由近到遠排序** @param startPoint* @param waypoints* @return*/public static List<GPSPoint> gpsPointsSort(GPSPoint startPoint, List<GPSPoint> waypoints) {Collections.sort(waypoints, new Comparator<GPSPoint>() {@Overridepublic int compare(GPSPoint o1, GPSPoint o2) {Double distance1 = CoordinateConversionUtil.getDistance(startPoint.getLng(), startPoint.getLat(), o1.getLng(), o1.getLat());Double distance2 = CoordinateConversionUtil.getDistance(startPoint.getLng(), startPoint.getLat(), o2.getLng(), o2.getLat());return distance1.compareTo(distance2);}});return waypoints;}/*** 軌跡糾偏接口,獲取駕駛軌跡路線,里程*/public static AmapResTrackingData getDrivingTracks(List<Map> locDates) {AmapResTrackingData resTrackingData = new AmapResTrackingData();try {JSONArray jsonArray = new JSONArray();locDates.stream().forEach(locDate -> {JSONObject jsonObject = new JSONObject();jsonObject.put("x", locDate.get("lgt")); //經度jsonObject.put("y", locDate.get("lat")); //緯度jsonObject.put("ag", locDate.get("direction")); //角度jsonObject.put("tm", locDate.get("time")); //時間jsonObject.put("sp", locDate.get("speed")); //速度jsonArray.add(jsonObject);});String response = HttpClientUtil.getInstance().postJSON(AMapAPIAddress.GRASP_ROAD_API_URL.ADDRESS + "?key=" + AMapAPIDevAccountInfo.KEY.value, jsonArray.toJSONString());JSONObject jb = JSON.parseObject(response);if (null != jb && jb.getJSONObject("data") != null) {resTrackingData = jb.getJSONObject("data").getJSONArray("distance").getJSONObject(0).toJavaObject(AmapResTrackingData.class);} else {logger.error("高德接口請求抓路失敗:{}", response);resTrackingData.setDistance(0L);} // resTrackingData.setPoints(locDates);} catch (Exception e) {logger.error("獲取軌跡糾偏", e);}return resTrackingData;}/*** 批量獲取駕車規劃*/public static List<AmapResPathData> getPathData(List<AmapBatchBO> batchBOS) {List<AmapResPathData> amapResPathDataList = new ArrayList<>();try {JSONObject batchReq = new JSONObject();int count = batchBOS.size();int index = 0;int step = 20;while (index < count) {List<AmapBatchBO> temp = batchBOS.subList(index, index + step <= count ? index + step : count);batchReq.put("ops", temp);String res = HttpClientUtil.getInstance().postJSON(AMapAPIAddress.BATCH_API_URL.ADDRESS, batchReq.toJSONString());JSONArray jsonArray = JSONObject.parseArray(res);Iterator itr = jsonArray.iterator();while (itr.hasNext()) {JSONObject jb = ((JSONObject) itr.next()).getJSONObject("body");if (null != jb && jb.getJSONObject("route") != null) {AmapResPathData amapResPathData = jb.getJSONObject("route").getJSONArray("paths").getJSONObject(0).toJavaObject(AmapResPathData.class);amapResPathDataList.add(amapResPathData);} else {AmapResPathData amapResPathData = new AmapResPathData();amapResPathData.setDistance(0L);amapResPathData.setDuration(0L);amapResPathDataList.add(amapResPathData);}}index += step;}} catch (Exception e) {logger.error("批量獲取駕車規劃", e);}return amapResPathDataList;}/*** 創建終端** @param key 請求服務權限標識* @param sid 服務的唯一編號* @param name 終端名稱* @param desc 終端描述* @param props 自定義字段*/public static String terminalAdd(String key, String sid, String name, String desc, String props) {Map<String, Object> params = new HashMap<>();params.put("key", key);params.put("sid", sid);params.put("name", name);params.put("desc", desc);params.put("props", props);return HttpClientUtil.getInstance().post(AMapAPIAddress.TERMINAL_ADD.ADDRESS, params);}/*** 創建軌跡, 創建一條軌跡,一個終端下最多可創建500000條軌跡。** @param key 請求服務權限標識* @param sid 查詢的服務ID* @param tid 設備唯一編號*/public static String trackTraceAdd(String key, String sid, String tid) {Map<String, Object> params = new HashMap<>();params.put("key", key);params.put("sid", sid);params.put("tid", tid);return HttpClientUtil.getInstance().post(AMapAPIAddress.TRACK_TRACE_ADD.ADDRESS, params);}/*** 獲取軌跡全部數據** @param tid 設備唯一編號(即t_car表里的Trid)* @param trid 軌跡唯一編號(即t_order表里的Trid)* @param startTime 起始時間, Unix時間戳(軌跡點的定位時間),需要精準到毫秒* @param endTime 結束時間, Unix時間戳(軌跡點的定位時間),需要精準到毫秒* @return*/public static TrackTraceSearchRes.Track getAllTrackTrace(String tid, String trid, Long startTime, Long endTime) {int pageNum = 1;int pageSize = 500;TrackTraceSearchRes res = trackTraceSearch(tid, trid, startTime, endTime, null, null, null, null, pageNum, pageSize);if (null == res || null == res.getData()) {logger.error("未查詢到軌跡數據");return null;} else {TrackTraceSearchRes.Track track = res.getData().getTracks().get(0);if (track != null && track.getCounts() > 0) {int totalPage = PageUtil.getTotalPage(pageSize, track.getCounts());for (int i = 1; i < totalPage; i++) {++pageNum;TrackTraceSearchRes res1 = trackTraceSearch(tid, trid, startTime, endTime, null, null, null, null, pageNum, pageSize);if (null == res1 || null == res1.getData()) {break;} else {TrackTraceSearchRes.Track track1 = res1.getData().getTracks().get(0);track.getPoints().addAll(track1.getPoints());}}}return track;}}/*** 查詢軌跡信息(里程、時間等)** @param key 請求服務權限標識* @param sid 查詢的服務ID* @param tid 設備唯一編號* @param trid 軌跡唯一編號* @param startTime 起始時間, Unix時間戳(軌跡點的定位時間),需要精準到毫秒* @param endTime 結束時間, Unix時間戳(軌跡點的定位時間),需要精準到毫秒, 結束時間不能大于當前時間,且距離開始時間不能超過24小時。 若軌跡較多,建議將時間段進行拆分。* @param correction 對軌跡進行處理* @param recoup 對軌跡進行補點 缺省值0, 0:代表用直線連接方式進行補點計算; 1:代表用correction的mode方式進行補點計算,當前只開放了driving。* @param gap 補點間距 缺省值為5公里,最小50米,最大10公里,單位:米。* @param isPoints 是否返回軌跡點信息 默認為返回(1),可以設置為不返回(0)* @param page 查詢頁數 缺省值1* @param pageSize 每頁點數 缺省值20,當page=1的時候起點、終點的個數不計算在內,pagesize最大值為1000。*/public static TrackTraceSearchRes trackTraceSearch(String tid, String trid, Long startTime, Long endTime, String correction,Integer recoup, Integer gap, Integer isPoints, Integer page, Integer pageSize) {Map<String, Object> params = new HashMap<>();params.put("key", AMapAPIDevAccountInfo.KEY.value);params.put("sid", AMapAPIDevAccountInfo.SID.value);params.put("tid", tid);params.put("trid", trid);params.put("starttime", startTime);params.put("endtime", endTime);params.put("correction", correction);params.put("recoup", recoup);params.put("gap", gap);params.put("ispoints", isPoints);params.put("page", page);params.put("pagesize", pageSize);String result = HttpClientUtil.getInstance().get(AMapAPIAddress.TRACK_TRACE_SEARCH.ADDRESS, params);return JSONObject.parseObject(result, TrackTraceSearchRes.class);}/*** 天氣接口 https://lbs.amap.com/api/webservice/guide/tools/weather-code/** @param key 請求服務權限標識* @param city 城市編碼 輸入城市的adcode,adcode信息可參考城市編碼表* @param extensions 氣象類型 可選值:base/all base:返回實況天氣 all:返回預報天氣* @param output 返回格式 可選值:JSON(默認),XML*/public static WeatherInfoRes getWeatherInfo(String key, String city, String extensions, String output) {Map<String, Object> params = new HashMap<>();params.put("key", key);params.put("city", city);params.put("extensions", extensions);params.put("output", output);String result = HttpClientUtil.getInstance().get(AMapAPIAddress.WEATHER_INFO.ADDRESS, params);return JSONObject.parseObject(result, WeatherInfoRes.class);}/*** 逆地理編碼** @param key 高德Key* @param location 經緯度坐標 傳入內容規則:經度在前,緯度在后,經緯度間以“,”分割,經緯度小數點后不要超過 6 位。如果需要解析多個經緯度的話,請用"|"進行間隔,并且將 batch 參數設置為 true,最多支持傳入 20 對坐標點。每對點坐標之間用"|"分割。* @param other 其他非必填參數,參考文檔:https://lbs.amap.com/api/webservice/guide/api/georegeo* @return*/public static ReGeoRes getLocationReGeo(String key, String location, Map<String, Object> other) {Map<String, Object> params = new HashMap<>();params.put("key", key);params.put("location", location);if (null != other) {other.forEach((keys, values) -> {params.put(keys, values);});}String result = HttpClientUtil.getInstance().get(AMapAPIAddress.GEOCODE_REGEO_API_URL.ADDRESS, params);return JSONObject.parseObject(result, ReGeoRes.class);}public static void main(String[] args) {GPSPoint a1 = new GPSPoint(Double.valueOf("117.130525"), Double.valueOf("29.258724"));GPSPoint a2 = new GPSPoint(Double.valueOf("117.214981"), Double.valueOf("29.293871"));GPSPoint b1 = new GPSPoint(Double.valueOf("117.1304215"), Double.valueOf("29.2585618"));GPSPoint b2 = new GPSPoint(Double.valueOf("117.216467"), Double.valueOf("29.289589"));List<GPSPoint> waypoints = new ArrayList<>();waypoints.add(a1);waypoints.add(a2);waypoints.add(b1);waypoints.add(b2);//自己加入行程后繞路里程AmapResPathData beforeJoin = AmapApi.getDriverNavPathData(a1,a2);AmapResPathData afterJoin = AmapApi.getDriverNavPathData(a1,a2, waypoints);BigDecimal detourMileagePec= BigDecimal.valueOf(afterJoin.getDistance() - beforeJoin.getDistance()).divide(BigDecimal.valueOf(beforeJoin.getDistance()),2,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));if (detourMileagePec.compareTo(BigDecimal.ZERO)==-1 ||detourMileagePec.compareTo(BigDecimal.valueOf(20))==1) {System.out.println("false");return;}//加入行程后對其他乘客的繞路里程beforeJoin = AmapApi.getDriverNavPathData(b1,b2);afterJoin = AmapApi.getDriverNavPathData(b1,b2, waypoints);if (BigDecimal.valueOf(afterJoin.getDistance() - beforeJoin.getDistance()).divide(BigDecimal.valueOf(beforeJoin.getDistance()),2,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).compareTo(BigDecimal.valueOf(20))==1) {System.out.println("false1");return;}} }總結
以上是生活随笔為你收集整理的高德地图服务端对接APIUtil的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python井字棋
- 下一篇: 5G高校教学实验室/实训室建设