Android高德地图路线规划,自定义图层(overlay),所有点和线刚好显示在屏幕中心

高德百度地图SDK路线规划包含:步行,公交,驾车,骑车。
搜索的结果是经纬度点信息Latlng(lat,lng)
功能
在地图map中将所有的点连线,并让该线能刚好被当前的地图层级包含,并且当前路线所在位置能刚好在地图中的中心位置。
效果图(以工具路线为例):
这里写图片描述
本例以高德地图进行研究(不包含室内)
思路:对高德地图SDK源码进行改进,根据路线的选择进行自定义Overlay和Markers实体工具类
下图是我建立的工程目录

这里写图片描述

步骤:
在overlay包下建立两个类,用来封装经纬度点和结果信息的处理及返回,如我可以判断路线中的拐点,及每一段路的连线颜色
比如:路线搜索结果路线是在A-B-C-D,四个街道上,其中A-B可能畅通,B-C可能拥挤,连线的颜色就需要不同,B点作为两个街道的拐点处,需要主动的显示showInfoWindow()

代码如下:
a类

package zhjx.com.annmet.map.overlay;

/**
 * Created by adminZPH on 2016/12/5.
 */
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import android.graphics.Bitmap;

import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;

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



class a {
    private static int a = 2048;

    public static LatLng a(LatLonPoint var0) {
        return new LatLng(var0.getLatitude(), var0.getLongitude());
    }

    public static ArrayList<LatLng> a(List<LatLonPoint> var0) {
        ArrayList var1 = new ArrayList();
        Iterator var2 = var0.iterator();

        while(var2.hasNext()) {
            LatLonPoint var3 = (LatLonPoint)var2.next();
            LatLng var4 = a(var3);
            var1.add(var4);
        }

        return var1;
    }

    public static Bitmap a(Bitmap var0, float var1) {
        if(var0 == null) {
            return null;
        } else {
            int var2 = (int)((float)var0.getWidth() * var1);
            int var3 = (int)((float)var0.getHeight() * var1);
            Bitmap var4 = Bitmap.createScaledBitmap(var0, var2, var3, true);
            return var4;
        }
    }
}

b类:

class b {
    protected List<Marker> stationMarkers = new ArrayList();
    protected List<Polyline> allPolyLines = new ArrayList();
    private Marker aa;
    private Marker b;
    protected LatLng startPoint;
    protected LatLng endPoint;
    protected AMap mAMap;
    private Context c;
    private Bitmap d;
    private Bitmap e;
    private Bitmap f;
    private Bitmap g;
    private Bitmap h;
    private AssetManager i;
    protected boolean mNodeIconVisible = true;

    public b(Context var1) {
        this.c = var1;
        this.i = this.c.getResources().getAssets();
    }

    public void removeFromMap() {
        if(this.aa != null) {
            this.aa.remove();
        }

        if(this.b != null) {
            this.b.remove();
        }

        Iterator var1 = this.stationMarkers.iterator();

        while(var1.hasNext()) {
            Marker var2 = (Marker)var1.next();
            var2.remove();
        }

        var1 = this.allPolyLines.iterator();

        while(var1.hasNext()) {
            Polyline var3 = (Polyline)var1.next();
            var3.remove();
        }

        this.a();
    }

    public void setNodeIconVisibility(boolean var1) {
        this.mNodeIconVisible = var1;
        Iterator var2 = this.stationMarkers.iterator();

        while(var2.hasNext()) {
            Marker var3 = (Marker)var2.next();
            var3.setVisible(var1);
        }

        this.mAMap.postInvalidate();
    }

    private void a() {
        if(this.d != null) {
            this.d.recycle();
            this.d = null;
        }

        if(this.e != null) {
            this.e.recycle();
            this.e = null;
        }

        if(this.f != null) {
            this.f.recycle();
            this.f = null;
        }

        if(this.g != null) {
            this.g.recycle();
            this.g = null;
        }

        if(this.h != null) {
            this.h.recycle();
            this.h = null;
        }

    }

    protected BitmapDescriptor getStartBitmapDescriptor() {
        return this.getBitDes(this.d, "amap_start.png");
    }

    protected BitmapDescriptor getEndBitmapDescriptor() {
        return this.getBitDes(this.e, "amap_end.png");
    }

    protected BitmapDescriptor getBusBitmapDescriptor() {
        return this.getBitDes(this.f, "amap_bus.png");
    }

    protected BitmapDescriptor getWalkBitmapDescriptor() {
        return this.getBitDes(this.g, "amap_man.png");
    }

    protected BitmapDescriptor getDriveBitmapDescriptor() {
        return this.getBitDes(this.h, "amap_car.png");
    }

    protected BitmapDescriptor getBitDes(Bitmap var1, String var2) {
        String var3 = "getBitDes";

        try {
            InputStream var4 = this.i.open(var2);
            var1 = BitmapFactory.decodeStream(var4);
            var1 = a.a(var1, p.a);
            var4.close();
        } catch (IOException var6) {
            cj.a(var6, "RouteOverlay", var3);
        } catch (Exception var7) {
            cj.a(var7, "RouteOverlay", var3);
        }

        return BitmapDescriptorFactory.fromBitmap(var1);
    }

    protected void addStartAndEndMarker() {
        this.aa = this.mAMap.addMarker((new MarkerOptions()).position(this.startPoint).icon(BitmapDescriptorFactory.fromBitmap(
                BitmapFactory.decodeResource(c.getResources(), R.mipmap.position))).title("您的位置"));
        /**
         * 让其自动显示终点的位置
         * */
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.position(this.endPoint);
        markerOptions.title("年会会场");
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(c.getResources(),
                R.mipmap.position)));
        this.b = this.mAMap.addMarker(markerOptions);
        this.b.showInfoWindow(); //主动显示indowindow
    }

    public void zoomToSpan() {
        if(this.startPoint != null && this.endPoint != null) {
            if(this.mAMap == null) {
                return;
            }

            LatLngBounds var1 = this.getLatLngBounds();
            this.mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(var1, 50));
        }

    }

    protected LatLngBounds getLatLngBounds() {
        LatLngBounds.Builder var1 = LatLngBounds.builder();
        var1.include(new LatLng(this.startPoint.latitude, this.startPoint.longitude));
        var1.include(new LatLng(this.endPoint.latitude, this.endPoint.longitude));
        return var1.build();
    }

    protected int getWalkColor() {
        return Color.parseColor("#d4020d");
    }

    protected int getBusColor() {
        return Color.parseColor("#00affe");
    }

    protected int getDriveColor() {
        return Color.parseColor("#537edc");
    }
}

公交路线的自定义图层

package zhjx.com.annmet.map.overlay;

import android.content.Context;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.amap.api.services.busline.BusStationItem;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusStep;
import com.amap.api.services.route.RouteBusLineItem;
import com.amap.api.services.route.RouteBusWalkItem;
import com.amap.api.services.route.WalkStep;

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

/**
 * Created by adminZPH on 2016/12/7.
 */

public class MyBusRouteOverlay extends b {
    private BusPath aa;
    private LatLng b;

    public MyBusRouteOverlay(Context var1, AMap var2, BusPath var3, LatLonPoint var4, LatLonPoint var5) {
        super(var1);
        this.aa = var3;
        this.startPoint = a.a(var4);
        this.endPoint = a.a(var5);
        this.mAMap = var2;
    }

    public void addToMap() {
        try {
            List var1 = this.aa.getSteps();

            for(int var2 = 0; var2 < var1.size(); ++var2) {
                BusStep var3 = (BusStep)var1.get(var2);
                if(var2 < var1.size() - 1) {
                    BusStep var4 = (BusStep)var1.get(var2 + 1);
                    if(var3.getWalk() != null && var3.getBusLine() != null) {
                        this.b(var3);
                    }

                    if(var3.getBusLine() != null && var4.getWalk() != null) {
                        this.c(var3, var4);
                    }

                    if(var3.getBusLine() != null && var4.getWalk() == null && var4.getBusLine() != null) {
                        this.b(var3, var4);
                    }

                    if(var3.getBusLine() != null && var4.getWalk() == null && var4.getBusLine() != null) {
                        this.a(var3, var4);
                    }
                }

                if(var3.getWalk() != null && var3.getWalk().getSteps().size() > 0) {
                    this.a(var3);
                } else if(var3.getBusLine() == null) {
                    Polyline var6 = this.a(this.b, this.endPoint);
                    this.allPolyLines.add(var6);
                }

                if(var3.getBusLine() != null) {
                    RouteBusLineItem var7 = var3.getBusLine();
                    this.a(var7);
                    this.b(var7);
                }
            }

            this.addStartAndEndMarker();
        } catch (Throwable var5) {
            var5.printStackTrace();
        }

    }

    private void a(BusStep var1) {
        RouteBusWalkItem var2 = var1.getWalk();
        List var3 = var2.getSteps();

        for(int var4 = 0; var4 < var3.size(); ++var4) {
            WalkStep var5 = (WalkStep)var3.get(var4);
            if(var4 == 0) {
                LatLng var6 = a.a((LatLonPoint)var5.getPolyline().get(0));
                String var7 = var5.getRoad();
                String var8 = this.b(var3);
                this.a(var6, var7, var8);
            }

            ArrayList var11 = a.a(var5.getPolyline());
            this.b = (LatLng)var11.get(var11.size() - 1);
            Polyline var12 = this.a((List)var11);
            this.allPolyLines.add(var12);
            if(var4 < var3.size() - 1) {
                LatLng var13 = (LatLng)var11.get(var11.size() - 1);
                LatLng var9 = a.a((LatLonPoint)((WalkStep)var3.get(var4 + 1)).getPolyline().get(0));
                if(!var13.equals(var9)) {
                    Polyline var10 = this.a(var13, var9);
                    this.allPolyLines.add(var10);
                }
            }
        }

    }

    private void a(LatLng var1, String var2, String var3) {
      /*  Marker var4 = this.mAMap.addMarker((new MarkerOptions()).position(var1).title(var2).snippet(var3).visible(this.mNodeIconVisible).anchor(0.5F, 0.5F).icon(this.getWalkBitmapDescriptor()));
        this.stationMarkers.add(var4);*/
    }

    private void a(RouteBusLineItem var1) {
        ArrayList var2 = a.a(var1.getPolyline());
        Polyline var3 = this.mAMap.addPolyline((new PolylineOptions()).addAll(var2).color(this.getBusColor()).width(this.getBuslineWidth()));
        this.allPolyLines.add(var3);
    }

    private void b(RouteBusLineItem var1) {
        BusStationItem var2 = var1.getDepartureBusStation();
        Marker var3 = this.mAMap.addMarker((new MarkerOptions()).position(a.a(var2.getLatLonPoint())).title(var1.getBusLineName()).snippet(this.c(var1)).anchor(0.5F, 0.5F).visible(this.mNodeIconVisible).icon(this.getBusBitmapDescriptor()));
        this.stationMarkers.add(var3);
    }

    private void a(BusStep var1, BusStep var2) {
        LatLng var3 = a.a(this.e(var1));
        LatLng var4 = a.a(this.f(var2));
        if(var4.latitude - var3.latitude > 1.0E-4D || var4.longitude - var3.longitude > 1.0E-4D) {
            this.drawLineArrow(var3, var4);
        }

    }

    private void b(BusStep var1, BusStep var2) {
        LatLonPoint var3 = this.e(var1);
        LatLng var4 = a.a(var3);
        LatLonPoint var5 = this.f(var2);
        LatLng var6 = a.a(var5);
        if(!var4.equals(var6)) {
            this.drawLineArrow(var4, var6);
        }

    }

    private void c(BusStep var1, BusStep var2) {
        LatLonPoint var3 = this.e(var1);
        LatLonPoint var4 = this.c(var2);
        if(!var3.equals(var4)) {
            Polyline var5 = this.a(var3, var4);
            this.allPolyLines.add(var5);
        }

    }

    private void b(BusStep var1) {
        LatLonPoint var2 = this.d(var1);
        LatLonPoint var3 = this.f(var1);
        if(!var2.equals(var3)) {
            Polyline var4 = this.a(var2, var3);
            this.allPolyLines.add(var4);
        }

    }

    private LatLonPoint c(BusStep var1) {
        return (LatLonPoint)((WalkStep)var1.getWalk().getSteps().get(0)).getPolyline().get(0);
    }

    private Polyline a(LatLonPoint var1, LatLonPoint var2) {
        LatLng var3 = a.a(var1);
        LatLng var4 = a.a(var2);
        return this.mAMap != null?this.a(var3, var4):null;
    }

    private Polyline a(LatLng var1, LatLng var2) {
        return this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{var1, var2}).width(this.getBuslineWidth()).color(this.getWalkColor()));
    }

    private Polyline a(List<LatLng> var1) {
        return this.mAMap.addPolyline((new PolylineOptions()).addAll(var1).color(this.getWalkColor()).width(this.getBuslineWidth()));
    }

    private String b(List<WalkStep> var1) {
        float var2 = 0.0F;

        WalkStep var4;
        for(Iterator var3 = var1.iterator(); var3.hasNext(); var2 += var4.getDistance()) {
            var4 = (WalkStep)var3.next();
        }

        return "步行" + var2 + "米";
    }

    public void drawLineArrow(LatLng var1, LatLng var2) {
        this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{var1, var2}).width(3.0F).color(this.getBusColor()).width(this.getBuslineWidth()));
    }

    private String c(RouteBusLineItem var1) {
        return "(" + var1.getDepartureBusStation().getBusStationName() + "-->" + var1.getArrivalBusStation().getBusStationName() + ") 经过" + (var1.getPassStationNum() + 1) + "站";
    }

    protected float getBuslineWidth() {
        return 10.0F;
    }

    private LatLonPoint d(BusStep var1) {
        List var2 = var1.getWalk().getSteps();
        WalkStep var3 = (WalkStep)var2.get(var2.size() - 1);
        List var4 = var3.getPolyline();
        return (LatLonPoint)var4.get(var4.size() - 1);
    }

    private LatLonPoint e(BusStep var1) {
        List var2 = var1.getBusLine().getPolyline();
        return (LatLonPoint)var2.get(var2.size() - 1);
    }

    private LatLonPoint f(BusStep var1) {
        return (LatLonPoint)var1.getBusLine().getPolyline().get(0);
    }
}

驾车路线的自定义图层

public class MyDrivingRouteOverlay extends b {
    private DrivePath aa;
    private Bitmap b;
    protected List<Marker> mPassByMarkers = new ArrayList();
    private List<LatLonPoint> c;
    private boolean d = true;

    public MyDrivingRouteOverlay(Context var1, AMap var2, DrivePath var3, LatLonPoint var4, LatLonPoint var5) {
        super(var1);
        this.mAMap = var2;
        this.aa = var3;
        this.startPoint = a.a(var4);
        this.endPoint = a.a(var5);
    }

    public MyDrivingRouteOverlay(Context var1, AMap var2, DrivePath var3, LatLonPoint var4, LatLonPoint var5, List<LatLonPoint> var6) {
        super(var1);
        this.mAMap = var2;
        this.aa = var3;
        this.startPoint = a.a(var4);
        this.endPoint = a.a(var5);
        this.c = var6;
    }

    public void addToMap() {
        List var1 = this.aa.getSteps();

        for(int var2 = 0; var2 < var1.size(); ++var2) {
            DriveStep var3 = (DriveStep)var1.get(var2);
            LatLng var4 = a.a((LatLonPoint)var3.getPolyline().get(0));
            LatLng var8;
            Polyline var10;
            if(var2 < var1.size() - 1) {
                if(var2 == 0) {
                    Polyline var5 = this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{this.startPoint, var4}).color(this.getDriveColor()).width(this.getBuslineWidth()));
                    this.allPolyLines.add(var5);
                }

                var8 = a.a((LatLonPoint)var3.getPolyline().get(var3.getPolyline().size() - 1));
                LatLng var6 = a.a((LatLonPoint)((DriveStep)var1.get(var2 + 1)).getPolyline().get(0));
                if(!var8.equals(var6)) {
                    Polyline var7 = this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{var8, var6}).color(this.getDriveColor()).width(this.getBuslineWidth()));
                    this.allPolyLines.add(var7);
                }
            } else {
                var8 = a.a((LatLonPoint)var3.getPolyline().get(var3.getPolyline().size() - 1));
                var10 = this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{var8, this.endPoint}).color(this.getDriveColor()).width(this.getBuslineWidth()));
                this.allPolyLines.add(var10);
            }

           /* Marker var9 = this.mAMap.addMarker((new MarkerOptions()).position(var4).title("方向:" + var3.getAction() + "\n道路:" + var3.getRoad()).snippet(var3.getInstruction()).anchor(0.5F, 0.5F).visible(this.mNodeIconVisible).icon(this.getDriveBitmapDescriptor()));
            this.stationMarkers.add(var9);*/
            var10 = this.mAMap.addPolyline((new PolylineOptions()).addAll(a.a(var3.getPolyline())).color(this.getDriveColor()).width(this.getBuslineWidth()));
            this.allPolyLines.add(var10);
        }

        this.a();
        this.addStartAndEndMarker();
    }

    private void a() {
        if(this.c != null && this.c.size() != 0) {
            Iterator var1 = this.c.iterator();

            while(var1.hasNext()) {
                LatLonPoint var2 = (LatLonPoint)var1.next();
                LatLng var3 = a.a(var2);
                Marker var4 = this.mAMap.addMarker((new MarkerOptions()).position(var3).title("途经点").visible(this.d).icon(this.getPassedByBitmapDescriptor()));
                this.mPassByMarkers.add(var4);
            }

        }
    }

    public void removeFromMap() {
        super.removeFromMap();
        Iterator var1 = this.mPassByMarkers.iterator();

        while(var1.hasNext()) {
            Marker var2 = (Marker)var1.next();
            var2.remove();
        }

    }

    public void setThroughPointIconVisibility(boolean var1) {
        this.d = var1;
        Iterator var2 = this.mPassByMarkers.iterator();

        while(var2.hasNext()) {
            Marker var3 = (Marker)var2.next();
            var3.setVisible(var1);
        }

        this.mAMap.postInvalidate();
    }

    protected float getBuslineWidth() {
        return 10.0F;
    }

    protected BitmapDescriptor getPassedByBitmapDescriptor() {
        return this.getBitDes(this.b, "amap_throughpoint.png");
    }

    protected LatLngBounds getLatLngBounds() {
        LatLngBounds.Builder var1 = LatLngBounds.builder();
        var1.include(new LatLng(this.startPoint.latitude, this.startPoint.longitude));
        var1.include(new LatLng(this.endPoint.latitude, this.endPoint.longitude));
        if(this.c != null && this.c.size() > 0) {
            for(int var2 = 0; var2 < this.c.size(); ++var2) {
                var1.include(new LatLng(((LatLonPoint)this.c.get(var2)).getLatitude(), ((LatLonPoint)this.c.get(var2)).getLongitude()));
            }
        }

        return var1.build();
    }
}

步行路线的自定义图层

public class MyWalkRouteOverlay extends b {
    private WalkPath aa;
    private Context c;
    public MyWalkRouteOverlay(Context var1, AMap var2, WalkPath var3, LatLonPoint var4, LatLonPoint var5) {
        super(var1);
        this.c=var1;
        this.mAMap = var2;
        this.aa = var3;

        this.startPoint = a.a(var4);
        this.endPoint = a.a(var5);
    }

    public void addToMap() {
        List var1 = this.aa.getSteps();

        for(int var2 = 0; var2 < var1.size(); ++var2) {
            WalkStep var3 = (WalkStep)var1.get(var2);
            LatLng var4 = a.a((LatLonPoint)var3.getPolyline().get(0));
            LatLng var8;
            Polyline var10;
            if(var2 < var1.size() - 1) {
                if(var2 == 0) {
                    Polyline var5 = this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{this.startPoint, var4}).color(this.getWalkColor()).width(this.getBuslineWidth()));
                    this.allPolyLines.add(var5);
                }

                var8 = a.a((LatLonPoint)var3.getPolyline().get(var3.getPolyline().size() - 1));
                LatLng var6 = a.a((LatLonPoint)((WalkStep)var1.get(var2 + 1)).getPolyline().get(0));
                if(!var8.equals(var6)) {
                    Polyline var7 = this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{var8, var6}).color(this.getWalkColor()).width(this.getBuslineWidth()));
                    this.allPolyLines.add(var7);
                }
            } else {
                var8 = a.a((LatLonPoint)var3.getPolyline().get(var3.getPolyline().size() - 1));
                var10 = this.mAMap.addPolyline((new PolylineOptions()).add(new LatLng[]{var8, this.endPoint}).color(this.getWalkColor()).width(this.getBuslineWidth()));
                this.allPolyLines.add(var10);
            }


            /**
             * 在这里设置是否用来添加步行人的图标
             * */
          /*  Marker var9 = this.mAMap.addMarker((new MarkerOptions()).position(var4).title("方向:" + var3.getAction() + "\n道路:" + var3.getRoad()).snippet(var3.getInstruction()).anchor(0.5F, 0.5F).visible(this.mNodeIconVisible).
                    icon(BitmapDescriptorFactory.fromBitmap(
                            BitmapFactory.decodeResource(c.getResources(), R.mipmap.walk_select_touming))));*/
//            this.stationMarkers.add(var9);



            var10 = this.mAMap.addPolyline((new PolylineOptions()).addAll(a.a(var3.getPolyline())).color(this.getWalkColor()).width(this.getBuslineWidth()));
            this.allPolyLines.add(var10);
        }

        this.addStartAndEndMarker();
    }
    /**
     * 返回要连线的宽度
     * */
    protected float getBuslineWidth() {
        return 4.0F;
    }
}

Activity界面,(本文仅给出步行的)

public class WalkRouteActivity extends BaseActivity   implements RouteSearch.OnRouteSearchListener  {
    private View headview;
    private TextView t1,t2;
    private Button detail;
    private ImageView daohang;
    private AMap aMap;
    private MapView mapView;
    private RouteSearch mRouteSearch;
    private WalkRouteResult mWalkRouteResult;//步行搜索结果
    private LatLonPoint mStartPoint;//起点,
    private LatLonPoint mEndPoint;//终点,
    private String mCurrentCityName = "北京";
    private ListView mBusResultList;
    private CustomProgressDialog customProgressDialog, customProgressDialog1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_walk_route);
        ExitApplication.getInstance().addActivity(this);
        initview();
        setHeadview();
        initmap(savedInstanceState);
        getIntentDate();
    }

    private void getIntentDate() {

        mStartPoint = new LatLonPoint(Double.valueOf(getIntent().getStringExtra("local_lat")), Double.valueOf(getIntent().getStringExtra("local_lng")));
        mEndPoint = new LatLonPoint(Contact.position.latitude, Contact.position.longitude);
        customProgressDialog = new CustomProgressDialog(this, "正在实时获取步行路线...", 0);
        customProgressDialog.show();
        onWalkClick();

    }

    public void onWalkClick() {
        searchRouteResult( RouteSearch.WalkDefault);
    }
    /**
     *
     * */
    private void searchRouteResult(int mode) {
        final RouteSearch.FromAndTo fromAndTo=new RouteSearch.FromAndTo(
                mStartPoint,mEndPoint);

        RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo, mode);
        // 异步路径规划步行模式查询
        mRouteSearch.calculateWalkRouteAsyn(query);


    }

    private void initmap(Bundle savedInstanceState) {

        mapView = (MapView) findViewById(R.id.route_map_walk);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);

        if (aMap == null) {
            aMap = mapView.getMap();
        }
    }

    private void setHeadview() {
        setstatusbarcolor();
        setHeaderTitle(headview,"步行路线");
        setHeaderImage(headview,  Contact.Position.LEFT, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initview() {
        headview=findViewById(R.id.headview);
        t1= (TextView) findViewById(R.id.drive_layout1_route);
        t2= (TextView) findViewById(R.id.drive_layout1_message);
        detail= (Button) findViewById(R.id.drive_layout1_detail);
        daohang= (ImageView) findViewById(R.id.daohang_png);

    }


    /**
     * 步行搜索结果:
     * */
    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    customProgressDialog.dismiss();
                    mWalkRouteResult = result;

                    final List<LatLng> list=new ArrayList<>();
                    for(int i=0;i<mWalkRouteResult.getPaths().size();++i){
                        for(int j=0;j<mWalkRouteResult.getPaths().get(i).getSteps().size();++j){
                           for(int k=0;k< mWalkRouteResult.getPaths().get(i).getSteps().get(j).getPolyline().size();++k){
                               list.add(new LatLng( mWalkRouteResult.getPaths().get(i).getSteps().get(j).getPolyline().get(k).getLatitude(),mWalkRouteResult.getPaths().get(i).getSteps().get(j).getPolyline().get(k).getLongitude()));

                           }

                        }

                    }

                    final WalkPath walkPath = mWalkRouteResult.getPaths().get(0);
/***

这里就使用我们的自定义图层进行显示,将搜索到的经纬度点进行画出来


*/
                    MyWalkRouteOverlay walkROuteOverlay = new MyWalkRouteOverlay(
                            this, aMap, walkPath, mWalkRouteResult.getStartPos(), mWalkRouteResult.getTargetPos());
                    //清空,添加,跳转
                    walkROuteOverlay.removeFromMap();

                    walkROuteOverlay.addToMap();
                    walkROuteOverlay.zoomToSpan();
                    int dis=(int) walkPath.getDistance();
                    int dur=(int) walkPath.getDuration();
                    t1.setText(""+AMapUtil.getFriendlyTime(dur)+"("+AMapUtil.getFriendlyLength(dis)+")");

                    daohang.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent =new Intent(WalkRouteActivity.this, MapFollowActivity.class);
                            intent.putExtra("walklist", (Serializable) list);
                            startActivity(intent);
                        }
                    });

                    detail.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent=new Intent(WalkRouteActivity.this,WalkRouteDetailActivity.class);
                            intent.putExtra("walk_path",walkPath);
                            intent.putExtra("walk_result",mWalkRouteResult);
                            startActivity(intent);
                        }
                    });

                    /*int
                    String des= ;
                    mRotueTimeDes.setText(des);
                    mRouteDetailDes.setVisibility(View.VISIBLE);
                   */


                }
            }
            else if (result != null && result.getPaths() == null) {
                customProgressDialog.dismiss();
                customProgressDialog1=new CustomProgressDialog(this,"暂无方案",1);
                customProgressDialog1.show();
                }

            } else {
            customProgressDialog.dismiss();
            customProgressDialog1=new CustomProgressDialog(this, AMapUtil.getErrorMessage(errorCode),1);
            customProgressDialog1.show();

            }


    }





    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

    }
    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}

布局文件(步行)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:clipToPadding="true"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent"
    tools:context=".map.navi.walk.WalkRouteActivity">
    <include layout="@layout/headview"
        android:id="@+id/headview"/>
    <com.amap.api.maps2d.MapView
        android:layout_below="@+id/headview"
        android:layout_above="@+id/buttom_walk"
        android:id="@+id/route_map_walk"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.amap.api.maps2d.MapView>
    <RelativeLayout
        android:id="@+id/buttom_walk"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="75dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:layout_toLeftOf="@+id/daohang_png"
            android:orientation="vertical">

            <TextView
                android:id="@+id/drive_layout1_route"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:maxLines="1"
                android:text=""
                android:textColor="@color/color_listviewitem"
                android:textSize="16sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="5dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/drive_layout1_message"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:maxLines="1"
                    android:text="具体路线信息请查看"
                    android:textColor="@color/color_jszc"
                    android:textSize="13sp" />


                <Button
                    android:id="@+id/drive_layout1_detail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@null"
                    android:text="详情>"
                    android:textColor="@color/color_car_text_lan"
                    android:textSize="13sp" />
            </LinearLayout>


        </LinearLayout>


        <ImageView
            android:id="@+id/daohang_png"
            android:layout_width="63dp"
            android:layout_height="63dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp"
            android:src="@mipmap/daohang_icon" />


    </RelativeLayout>

</RelativeLayout>

工具类

扫描二维码关注公众号,回复: 122649 查看本文章

AMapUtil


package zhjx.com.annmet.map.util;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusStep;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteBusLineItem;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import zhjx.com.annmet.R;
import zhjx.com.annmet.bean.DriveRouteBean;

public class AMapUtil {
    public static final String HtmlBlack = "#000000";
    public static final String HtmlGray = "#808080";

    /**
     * 判断edittext是否null
     */
    public static String checkEditText(EditText editText) {
        if (editText != null && editText.getText() != null
                && !(editText.getText().toString().trim().equals(""))) {
            return editText.getText().toString().trim();
        } else {
            return "";
        }
    }

    public static Spanned stringToSpan(String src) {
        return src == null ? null : Html.fromHtml(src.replace("\n", "<br />"));
    }

    public static String colorFont(String src, String color) {
        StringBuffer strBuf = new StringBuffer();

        strBuf.append("<font color=").append(color).append(">").append(src)
                .append("</font>");
        return strBuf.toString();
    }

    public static String makeHtmlNewLine() {
        return "<br />";
    }

    public static String makeHtmlSpace(int number) {
        final String space = "&nbsp;";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < number; i++) {
            result.append(space);
        }
        return result.toString();
    }

    public static String getFriendlyLength(int lenMeter) {
        if (lenMeter > 10000) // 10 km
        {
            int dis = lenMeter / 1000;
            return dis + ChString.Kilometer;
        }

        if (lenMeter > 1000) {
            float dis = (float) lenMeter / 1000;
            DecimalFormat fnum = new DecimalFormat("##0.0");
            String dstr = fnum.format(dis);
            return dstr + ChString.Kilometer;
        }

        if (lenMeter > 100) {
            int dis = lenMeter / 50 * 50;
            return dis + ChString.Meter;
        }

        int dis = lenMeter / 10 * 10;
        if (dis == 0) {
            dis = 10;
        }

        return dis + ChString.Meter;
    }

    public static boolean IsEmptyOrNullString(String s) {
        return (s == null) || (s.trim().length() == 0);
    }

    /**
     * 把LatLng对象转化为LatLonPoint对象
     */
    public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
        return new LatLonPoint(latlon.latitude, latlon.longitude);
    }

    /**
     * 把LatLonPoint对象转化为LatLon对象
     */
    public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
    }

    /**
     * 把集合体的LatLonPoint转化为集合体的LatLng
     */
    public static ArrayList<LatLng> convertArrList(List<LatLonPoint> shapes) {
        ArrayList<LatLng> lineShapes = new ArrayList<LatLng>();
        for (LatLonPoint point : shapes) {
            LatLng latLngTemp = AMapUtil.convertToLatLng(point);
            lineShapes.add(latLngTemp);
        }
        return lineShapes;
    }

    /**
     * long类型时间格式化
     */
    public static String convertToTime(long time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        return df.format(date);
    }

    public static String getFriendlyTime(int second) {
        if (second > 3600) {
            int hour = second / 3600;
            int miniate = (second % 3600) / 60;
            return hour + "小时" + miniate + "分钟";
        }
        if (second >= 60) {
            int miniate = second / 60;
            return miniate + "分钟";
        }
        return second + "秒";
    }

    //路径规划方向指示和图片对应
    public static int getDriveActionID(String actionName) {
        if (actionName == null || actionName.equals("")) {
            return R.mipmap.drive_alone_big;
        }
        if ("左转".equals(actionName)) {
            return R.mipmap.drive_left_deep_big;
        }
        if ("右转".equals(actionName)) {
            return R.mipmap.drive_right_deep_big;
        }
        if ("向左前方行驶".equals(actionName) || "靠左".equals(actionName)) {
            return R.mipmap.drive_left_big;
        }
        if ("向右前方行驶".equals(actionName) || "靠右".equals(actionName)) {
            return R.mipmap.drive_right_big;
        }
        if ("向左后方行驶".equals(actionName) || "左转调头".equals(actionName)) {
            return R.mipmap.dir7;
        }
        if ("向右后方行驶".equals(actionName)) {
            return R.mipmap.dir8;
        }
        if ("直行".equals(actionName)) {
            return R.mipmap.drive_alone_big;
        }
        if ("减速行驶".equals(actionName)) {
            return R.mipmap.drive_alone_big;
        }
        return R.mipmap.drive_alone_big;
    }

    public static int getWalkActionID(String actionName) {
        if (actionName == null || actionName.equals("")) {
            return R.mipmap.dir13;
        }
        if ("左转".equals(actionName)) {
            return R.mipmap.dir2;
        }
        if ("右转".equals(actionName)) {
            return R.mipmap.dir1;
        }
        if ("向左前方".equals(actionName) || "靠左".equals(actionName)) {
            return R.mipmap.dir6;
        }
        if ("向右前方".equals(actionName) || "靠右".equals(actionName)) {
            return R.mipmap.dir5;
        }
        if ("向左后方".equals(actionName)) {
            return R.mipmap.dir7;
        }
        if ("向右后方".equals(actionName)) {
            return R.mipmap.dir8;
        }
        if ("直行".equals(actionName)) {
            return R.mipmap.dir3;
        }
        if ("通过人行横道".equals(actionName)) {
            return R.mipmap.dir9;
        }
        if ("通过过街天桥".equals(actionName)) {
            return R.mipmap.dir11;
        }
        if ("通过地下通道".equals(actionName)) {
            return R.mipmap.dir10;
        }

        return R.mipmap.dir13;
    }

    public static String getBusPathTitle(BusPath busPath) {
        if (busPath == null) {
            return String.valueOf("");
        }
        List<BusStep> busSetps = busPath.getSteps();
        if (busSetps == null) {
            return String.valueOf("");
        }
        StringBuffer sb = new StringBuffer();
        for (BusStep busStep : busSetps) {
            if (busStep.getBusLines().size() > 0) {
                RouteBusLineItem busline = busStep.getBusLines().get(0);
                if (busline == null) {
                    continue;
                }
                String buslineName = getSimpleBusLineName(busline.getBusLineName());
                sb.append(buslineName);
                sb.append(" > ");
            }
        }
        return sb.substring(0, sb.length() - 3);
    }

    public static String getBusPathDes(BusPath busPath) {
        if (busPath == null) {
            return String.valueOf("");
        }
        long second = busPath.getDuration();
        String time = getFriendlyTime((int) second);
        float subDistance = busPath.getDistance();
        String subDis = getFriendlyLength((int) subDistance);
        float walkDistance = busPath.getWalkDistance();
        String walkDis = getFriendlyLength((int) walkDistance);
        return String.valueOf(time + " | " + subDis + " | 步行" + walkDis);
    }

    public static String getSimpleBusLineName(String busLineName) {
        if (busLineName == null) {
            return String.valueOf("");
        }
        return busLineName.replaceAll("\\(.*?\\)", "");
    }

    /**
     * 公交的上车站
     */
    public static String getBusShangCheZhan(BusPath busPath) {
        if (busPath == null) {
            return String.valueOf("暂无");
        }
        String chezhan = busPath.getSteps().get(0).getBusLines().get(0).getDepartureBusStation().getBusStationName();
        if (TextUtils.isEmpty(chezhan)) {
            return String.valueOf("暂无");
        } else
            return chezhan;

    }

    /**
     * 对搜索出来的驾车路线中的路段进行去除重复及排序
     */
    public static List<String> SelectStringAndSort(List<String> roads) {
        List<String> list = roads;
        for (int i = 0; i < list.size(); ++i) {
            for (int j = list.size() - 1; j > i; --j) {
                if (list.get(i).equals(list.get(j))) {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    /***
     * 高德地图错误代码的原因
     * */

    public static String getErrorMessage(int coreid){
        switch (coreid){
            case 3003: return  "距离太远了";
            case 1802: return "网络异常";
            case 1804: return "网络异常";
            case 3000: return "起点或终点不在中国境内";
            case 3001: return "附近没有路";
            case 3002: return "道路连通关系异常";
            default: return "服务器异常";
        }
    }

    public static DriveRouteBean getALlMessageFromDriveRoute(DriveRouteResult mDriveRouteResult){
        DriveRouteBean bean=new DriveRouteBean();
        int dis = (int) mDriveRouteResult.getPaths().get(0).getDistance();//距离
        int dur = (int) mDriveRouteResult.getPaths().get(0).getDuration();//时长
        String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
        int taxiCost = (int) mDriveRouteResult.getTaxiCost();
        List<String> roads = new ArrayList<>();
        for (int j = 0; j < mDriveRouteResult.getPaths().get(0).getSteps().size(); ++j) {
            if (!TextUtils.isEmpty(mDriveRouteResult.getPaths().get(0).getSteps().get(j).getRoad()))
                roads.add(mDriveRouteResult.getPaths().get(0).getSteps().get(j).getRoad());
        }
        Log.i("TAG", "排序去除重复前得到的数据是:" + roads.toString());
        roads =SelectStringAndSort(roads);
        Log.i("TAG", "排序去除重复后得到的数据是:" + roads.toString());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < roads.size(); ++i) {
            sb.append(roads.get(i));
            if (i != roads.size() - 1) {
                sb.append(">");
            }
        }


        bean.setDistance(getFriendlyLength(dis));
        bean.setDistime(getFriendlyTime(dur));
        bean.setCoastcar("打车约" + taxiCost + "元");
        bean.setRoute(sb.toString());
        bean.setDrivePath(mDriveRouteResult.getPaths().get(0));



        return bean;
    }

}

对于驾车路线具体使用和步行基本一致,工具路线略微有点不一致,主要是搜素结果包含每一站的信息,比如:A到B站牌搜索结果是5个经纬度点,其中包含AB两点的信息
更多疑问请咨询我
-这片海

猜你喜欢

转载自blog.csdn.net/qq_24536171/article/details/66973065