上篇信息我们讲到了自定义marker,这篇信息我们这边来使用自定义导航路线规划。
结合上篇的信息,我们将需要用到的点通过marker集合的方式在地图中显示出来,下来就是二点之间实时路线的规划。
api 中原本有设置途经点的方法,但是途经点的方法支持传入的点比较少(20个);项目中的坐标点不确定,所以采用直接划线的方式。
1、我们需要用到map中的RouteSearch 这个类,来进行搜索功能。初始化参数:
//初始化routeSearch 方法
RouteSearch routeSearch = new RouteSearch(this);
}
2、通过遍历还进行两个点之间指定路线的查询,然后调用RouteSearch.DriveRouteQuery生成 query查询对象, 然后进行异步查询routeSearch.calculateDriveRouteAsyn(query);
for(int i = 0; i<latLngs.size();i++){
if(i< latLngs.size()-1){
LatLng latLngStart = latLngs.get(i);
LatLng latLngEnd = latLngs.get(i+1);
LatLonPoint mStartPoint = new LatLonPoint(latLngStart.latitude,latLngStart.longitude);
LatLonPoint mEndPoint = new LatLonPoint(latLngEnd.latitude,latLngEnd.longitude);
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint,mEndPoint);
RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_MULTI_STRATEGY_FASTEST_SHORTEST_AVOID_CONGESTION, null, null, "");
routeSearch.calculateDriveRouteAsyn(query);
}
}
3、查询结果会通过注册的监听方法实现回调,在onDriveRouteSearched()方法内进行事件处理。
routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
@Override
public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
}
@Override
public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
//获取查询结果的路径集合,如果多条路径会返回集合数组,我们这里默认获取第一条路线
List<DrivePath> drivePaths = driveRouteResult.getPaths();
//获取第一条推荐路线的段落集合
List<DriveStep> driveSteps = drivePaths.get(0).getSteps();
List<LatLng> latLngs = new ArrayList();
//通过遍历,将DriveStep 里面的集合坐标点放入latLngs 内
for(DriveStep driveStep : driveSteps){
List<LatLonPoint> latLonPoints = driveStep.getPolyline();
for(LatLonPoint latLonPoint : latLonPoints){
LatLng latLng1 = new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude());
latLngs.add(latLng1);
}
}
//判断集合不为空,进行路线的绘制
if(clientDetailsList.size()> 0){
aMap.addPolyline(new PolylineOptions().
addAll(latLngs).width(10).color(Color.argb(255, 71, 204, 160)));
}
}
@Override
public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
}
@Override
public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
}
});
绘制路线我们使用高德提供的接口aMap.addPolyline(PolylineOptions var1);PolylineOptions 类为绘制路线的属性类,
addAll(List)为坐标集合;width(10) 为线的宽度;color(Color.argb(255, 71, 204, 160)))为线的颜色。
至此,路线的自定义规划和绘制就完成了,仅供参考!