在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返回的是单位是米和秒,我们把单位转换一下
@Override
public 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("暂无定位信息");
}
}
至此大功告成,就成功的拿到驾车行驶距离和时间!