android 百度地图画路线(驾车路线)


其实下面的代码网上都可以找到,但是“DrivingRouteOverlay”这个类不知道哪来的我也是找了很久才找到的;到百度地图官网下载所有的sdk在demo里面有
baidu.mapapi.overlayutil这里面有,下面直接贴代码。
private void driving(Double myLat,Double myLon){
//其中myLar myLon 是起点的经纬度  lat和lon是终点的经纬度
    RoutePlanSearch newInstance = RoutePlanSearch.newInstance();
    newInstance.setOnGetRoutePlanResultListener(new MyListener());

    //驾车路线
    DrivingRoutePlanOption drivingOption = new DrivingRoutePlanOption();
    PlanNode from = PlanNode.withLocation(new LatLng(myLat, myLon));  //设置起点世界之窗
    PlanNode to = PlanNode.withLocation(new LatLng(Double.valueOf(lat),Double.valueOf(lon)));  
    drivingOption.from(from);
    drivingOption.to(to);
    drivingOption.policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_DIS_FIRST); //方案:最短距离 这个自己设置 比如时间短之类的
    newInstance.drivingSearch(drivingOption);
}
class MyListener implements OnGetRoutePlanResultListener {

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        //驾车
        if(result == null || SearchResult.ERRORNO.RESULT_NOT_FOUND == result.error){
            Toast.makeText(getApplicationContext(), "未搜索到结果", Toast.LENGTH_LONG).show();
            return;
        }
        //开始处理结果了
        DrivingRouteOverlay overlay = new MyDrivingOverlay(mBaiduMap);
        mBaiduMap.setOnMarkerClickListener(overlay);// 把事件传递给overlay
        overlay.setData(result.getRouteLines().get(0));// 设置线路为第一条
        overlay.addToMap();
        overlay.zoomToSpan();
    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult result) {
        // 公交换乘

    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult result) {
        // 步行

    }

}
class MyDrivingOverlay extends DrivingRouteOverlay {

    public MyDrivingOverlay(BaiduMap arg0) {
        super(arg0);
    }
// 
icon_st
icon_en这两个图片百度demo里有如果用null的话有的机子会出错
@Override public BitmapDescriptor getStartMarker() { //覆写此方法以改变默认起点图标 return BitmapDescriptorFactory. fromResource(R.drawable. icon_st) ; } @Override public BitmapDescriptor getTerminalMarker() { //覆写此方法以改变默认终点图标 return BitmapDescriptorFactory. fromResource(R.drawable. icon_en) ; }}
//这个在百度地图demo里面有
 
  
public class DrivingRouteOverlay extends OverlayManager {

    private DrivingRouteLine mRouteLine = null;
    boolean focus = false;

    /**
     * 构造函数
     * 
     * @param baiduMap
     *            该DrivingRouteOvelray引用的 BaiduMap
     */
    public DrivingRouteOverlay(BaiduMap baiduMap) {
        super(baiduMap);
    }

    @Override
    public final List getOverlayOptions() {
        if (mRouteLine == null) {
            return null;
        }

        List overlayOptionses = new ArrayList();
        // step node
        if (mRouteLine.getAllStep() != null
                && mRouteLine.getAllStep().size() > 0) {
            
            for (DrivingStep step : mRouteLine.getAllStep()) {
                Bundle b = new Bundle();
                b.putInt("index", mRouteLine.getAllStep().indexOf(step));
                if (step.getEntrance() != null) {
                    overlayOptionses.add((new MarkerOptions())
                            .position(step.getEntrance().getLocation())
                                    .anchor(0.5f, 0.5f)
                                            .zIndex(10)
                                                    .rotate((360 - step.getDirection()))
                                                            .extraInfo(b)
                                                                    .icon(BitmapDescriptorFactory
                                                                            .fromAssetWithDpi("Icon_line_node.png")));
                }
                // 最后路段绘制出口点
                if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine
                        .getAllStep().size() - 1) && step.getExit() != null) {
                    overlayOptionses.add((new MarkerOptions())
                            .position(step.getExit().getLocation())
                                    .anchor(0.5f, 0.5f)
                                            .zIndex(10)
                                                    .icon(BitmapDescriptorFactory
                                                            .fromAssetWithDpi("Icon_line_node.png")));

                }
            }
        }

        if (mRouteLine.getStarting() != null) {
            overlayOptionses.add((new MarkerOptions())
                    .position(mRouteLine.getStarting().getLocation())
                            .icon(getStartMarker() != null ? getStartMarker() :
                                    BitmapDescriptorFactory
                                            .fromAssetWithDpi("Icon_start.png")).zIndex(10));
        }
        if (mRouteLine.getTerminal() != null) {
            overlayOptionses
                    .add((new MarkerOptions())
                            .position(mRouteLine.getTerminal().getLocation())
                                    .icon(getTerminalMarker() != null ? getTerminalMarker() :
                                            BitmapDescriptorFactory
                                                    .fromAssetWithDpi("Icon_end.png"))
                                                            .zIndex(10));
        }
        // poly line
        if (mRouteLine.getAllStep() != null
                && mRouteLine.getAllStep().size() > 0) {
        
            List steps = mRouteLine.getAllStep();
            int stepNum = steps.size();
            
            
            List points = new ArrayList();
            ArrayList traffics = new ArrayList();
            int totalTraffic = 0;
            for (int i = 0; i < stepNum ; i++) {
                if (i == stepNum - 1) {
                    points.addAll(steps.get(i).getWayPoints());
                } else {
                    points.addAll(steps.get(i).getWayPoints().subList(0, steps.get(i).getWayPoints().size() - 1));
                }
                
                totalTraffic += steps.get(i).getWayPoints().size() - 1;
                if (steps.get(i).getTrafficList() != null && steps.get(i).getTrafficList().length > 0) {
                    for (int j = 0;j < steps.get(i).getTrafficList().length;j++) {
                        traffics.add(steps.get(i).getTrafficList()[j]);
                    }
                }
            }
            
//            Bundle indexList = new Bundle();
//            if (traffics.size() > 0) {
//                int raffic[] = new int[traffics.size()];
//                int index = 0;
//                for (Integer tempTraff : traffics) {
//                    raffic[index] = tempTraff.intValue();
//                    index++;
//                }
//                indexList.putIntArray("indexs", raffic);
//            }
            boolean isDotLine = false;
            
            if (traffics != null && traffics.size() > 0) {
                isDotLine = true;
            }
            PolylineOptions option = new PolylineOptions().points(points).textureIndex(traffics)
                    .width(7).dottedLine(isDotLine).focus(true)
                        .color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0);
            if (isDotLine) {
                option.customTextureList(getCustomTextureList());
            }
            overlayOptionses.add(option);
        }
        return overlayOptionses;
    }

    /**
     * 设置路线数据
     * 
     * @param routeLine
     *            路线数据
     */
    public void setData(DrivingRouteLine routeLine) {
        this.mRouteLine = routeLine;
    }

    /**
     * 覆写此方法以改变默认起点图标
     * 
     * @return 起点图标
     */
    public BitmapDescriptor getStartMarker() {
        return null;
    }

    /**
     * 覆写此方法以改变默认绘制颜色
     * @return 线颜色
     */
    public int getLineColor() {
        return 0;
    }
    public List getCustomTextureList() {
        ArrayList list = new ArrayList();
        list.add(BitmapDescriptorFactory.fromAsset("Icon_road_blue_arrow.png"));
        list.add(BitmapDescriptorFactory.fromAsset("Icon_road_green_arrow.png"));
        list.add(BitmapDescriptorFactory.fromAsset("Icon_road_yellow_arrow.png"));
        list.add(BitmapDescriptorFactory.fromAsset("Icon_road_red_arrow.png"));
        list.add(BitmapDescriptorFactory.fromAsset("Icon_road_nofocus.png"));
        return list;
    }
    /**
     * 覆写此方法以改变默认终点图标
     * 
     * @return 终点图标
     */
    public BitmapDescriptor getTerminalMarker() {
        return null;
    }

    /**
     * 覆写此方法以改变默认点击处理
     * 
     * @param i
     *            线路节点的 index
     * @return 是否处理了该点击事件
     */
    public boolean onRouteNodeClick(int i) {
        if (mRouteLine.getAllStep() != null
                && mRouteLine.getAllStep().get(i) != null) {
            Log.i("baidumapsdk", "DrivingRouteOverlay onRouteNodeClick");
        }
        return false;
    }

    @Override
    public final boolean onMarkerClick(Marker marker) {
        for (Overlay mMarker : mOverlayList) {
            if (mMarker instanceof Marker && mMarker.equals(marker)) {
                if (marker.getExtraInfo() != null) {
                    onRouteNodeClick(marker.getExtraInfo().getInt("index"));
                }
            }
        }
        return true;
    }

    @Override
    public boolean onPolylineClick(Polyline polyline) {
        boolean flag = false;
        for (Overlay mPolyline : mOverlayList) {
            if (mPolyline instanceof Polyline && mPolyline.equals(polyline)) {
                // 选中
                flag = true;
                break;
            }
        }
        setFocus(flag);
        return true;
    }

    public void setFocus(boolean flag) {
        focus = flag;
        for (Overlay mPolyline : mOverlayList) {
            if (mPolyline instanceof Polyline) {
                // 选中
                ((Polyline) mPolyline).setFocus(flag);

                break;
            }
        }

    }
}


import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnPolylineClickListener;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLngBounds;

import java.util.ArrayList;
import java.util.List;

import static com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;

/**
 * 该类提供一个能够显示和管理多个Overlay的基类
 * 

* 复写{@link #getOverlayOptions()} 设置欲显示和管理的Overlay列表 *

*

* 通过 * {@link BaiduMap#setOnMarkerClickListener(OnMarkerClickListener)} * 将覆盖物点击事件传递给OverlayManager后,OverlayManager才能响应点击事件。 *

* 复写{@link #onMarkerClick(Marker)} 处理Marker点击事件 *

*/ public abstract class OverlayManager implements OnMarkerClickListener, OnPolylineClickListener { BaiduMap mBaiduMap = null; private List mOverlayOptionList = null; List mOverlayList = null; /** * 通过一个BaiduMap 对象构造 * * @param baiduMap */ public OverlayManager(BaiduMap baiduMap) { mBaiduMap = baiduMap; // mBaiduMap.setOnMarkerClickListener(this); if (mOverlayOptionList == null) { mOverlayOptionList = new ArrayList(); } if (mOverlayList == null) { mOverlayList = new ArrayList(); } } /** * 覆写此方法设置要管理的Overlay列表 * * @return 管理的Overlay列表 */ public abstract List getOverlayOptions(); /** * 将所有Overlay 添加到地图上 */ public final void addToMap() { if (mBaiduMap == null) { return; } removeFromMap(); List overlayOptions = getOverlayOptions(); if (overlayOptions != null) { mOverlayOptionList.addAll(getOverlayOptions()); } for (OverlayOptions option : mOverlayOptionList) { mOverlayList.add(mBaiduMap.addOverlay(option)); } } /** * 将所有Overlay 从 地图上消除 */ public final void removeFromMap() { if (mBaiduMap == null) { return; } for (Overlay marker : mOverlayList) { marker.remove(); } mOverlayOptionList.clear(); mOverlayList.clear(); } /** * 缩放地图,使所有Overlay都在合适的视野内 *

* 注: 该方法只对Marker类型的overlay有效 *

* */ public void zoomToSpan() { if (mBaiduMap == null) { return; } if (mOverlayList.size() > 0) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (Overlay overlay : mOverlayList) { // polyline 中的点可能太多,只按marker 缩放 if (overlay instanceof Marker) { builder.include(((Marker) overlay).getPosition()); } } mBaiduMap.setMapStatus(MapStatusUpdateFactory .newLatLngBounds(builder.build())); } } }

 
 

你可能感兴趣的:(android)