生活随笔
收集整理的這篇文章主要介紹了
Android高德地图计算驾车距离及时间
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Android開發過程中大家可能會遇到這樣的需求,根據兩個位置的坐標計算行駛距離和時間,如下圖 那這里改怎么實現呢?小編也是各種百度,最后發現高德地圖自帶了計算的API
引用高德搜索包,在app目錄下
//搜索功能implementation 'com.amap.api:search:latest.integration'
實例化 DistanceSearch distanceSearch; DistanceSearch.DistanceQuery distanceQuery;
distanceQuery = new DistanceSearch.DistanceQuery();distanceSearch = new DistanceSearch(this);
設置起點,終點經緯度繼承DistanceSearch.OnDistanceSearchListener的回調
LatLonPoint start = new LatLonPoint(Double.valueOf(start_lat), Double.valueOf(start_lng));LatLonPoint dest = new LatLonPoint(Double.valueOf(lat), Double.valueOf(lng));List<LatLonPoint> latLonPoints = new ArrayList<LatLonPoint>();latLonPoints.add(start);distanceQuery.setOrigins(latLonPoints);distanceQuery.setDestination(dest);
// 設置測量方式,支持直線和駕車distanceQuery.setType(DistanceSearch.TYPE_DRIVING_DISTANCE);distanceSearch.calculateRouteDistanceAsyn(distanceQuery);distanceSearch.setDistanceSearchListener(this);
DistanceSearch.OnDistanceSearchListener返回的DistanceResult返回信息就是我們要的數據,DistanceResult返回的是單位是米和秒,我們把單位轉換一下
@Overridepublic void onDistanceSearched(DistanceResult distanceResult, int i) {mStatusView.showContentView();
// Log.d("距離", "onDistanceSearched: " + i);if (i == 1000) {String time_string;//距離米String distance = Integer.valueOf((int) distanceResult.getDistanceResults().get(0).getDistance()) / 1000 + "";//時間秒 轉分鐘/*int time = (int) distanceResult.getDistanceResults().get(0).getDuration() / 60;Log.d("距離", "onDistanceSearched: " + distance + " " + time);int hours = (int) Math.floor(time / 60);int minute = time % 60;if (hours > 0) {time_string = time + "小時" + minute + "分鐘";} else {time_string = minute + "分鐘";}*/long second = (long) distanceResult.getDistanceResults().get(0).getDuration();long days = second / 86400; //轉換天數second = second % 86400; //剩余秒數long hours = second / 3600; //轉換小時second = second % 3600; //剩余秒數long minutes = second / 60; //轉換分鐘second = second % 60;if (days > 0) {time_string = days + "天" + hours + "小時" + minutes + "分鐘";} else if (hours > 0) {time_string = hours + "小時" + minutes + "分鐘";} else {time_string = minutes + "分鐘";}mTvDistance.setText("距您約" + distance + "公里,駕車約" + time_string);} else {mTvDistance.setText("暫無定位信息");}}
至此大功告成,就成功的拿到駕車行駛距離和時間!
總結
以上是生活随笔 為你收集整理的Android高德地图计算驾车距离及时间 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。