AndroidStudio下加入百度地圖的使用(四)——路線規劃

上一章中咱們已經完成了API經常使用的方法及常量屬性的使用,這一章向你們介紹一下地圖的重要功能-路線規劃。node

(1) 定義API中的路線查詢類:android

RoutePlanSearch  mSearch = RoutePlanSearch.newInstance();
mSearch.drivingSearch().;//駕車路線
mSearch.transitSearch();//公交路線
mSearch.walkingSearch();//步行路線

(2) 設置起點和終點web

PlanNode stNode = PlanNode.withCityNameAndPlaceName("",「」)      PlanNode  enNode  =  PlanNode.withCityNameAndPlaceName("", 「」);

(3) 實現OnGetRoutePlanResultListener監聽api

當路線結果發生變化的時候要重寫 駕車路線 公交路線 步行路線這3個方法app

public void onGetTransitRouteResult(TransitRouteResult result) {}
public void onGetWalkingRouteResult(WalkingRouteResult result) {}
public void onGetDrivingRouteResult(DrivingRouteResult result) {}

效果:ide

下面咱們來具體使用一下佈局

第一步:編寫佈局,沒有什麼特殊的地方

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="起點:" />
        <EditText
            android:id="@+id/start"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:text="煙臺萊山區科技大廈" >
            <requestFocus />
        </EditText>
    </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="終點:" />
        <EditText
            android:id="@+id/end"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:text="煙臺大學" >
            <requestFocus />
        </EditText>
    </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:layout_marginTop="5dip"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/drive"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_weight="1.0"
            android:onClick="SearchButtonProcess"
            android:text="駕車搜索" />
        <Button
            android:id="@+id/transit"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_weight="1.0"
            android:onClick="SearchButtonProcess"
            android:text="公交搜索" />
        <Button
            android:id="@+id/walk"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_weight="1.0"
            android:onClick="SearchButtonProcess"
            android:text="步行搜索" />
    </LinearLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <com.baidu.mapapi.map.MapView
            android:id="@+id/map"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:clickable="true" />
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_alignWithParentIfMissing="false"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dip"
            android:orientation="vertical" >
            <Button
                android:id="@+id/customicon"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginTop="10dip"
                android:layout_weight="1.0"
                android:onClick="changeRouteIcon"
                android:text="自定義起終點圖標" />
        </LinearLayout>
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignWithParentIfMissing="false"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="false"
            android:layout_marginBottom="10dip" >
            <Button
                android:id="@+id/pre"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginLeft="2dip"
                android:layout_marginRight="2dip"
                android:layout_weight="1.0"
                android:background="@drawable/pre_"
                android:onClick="nodeClick" />
            <Button
                android:id="@+id/next"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginLeft="2dip"
                android:layout_marginRight="2dip"
                android:layout_weight="1.0"
                android:background="@drawable/next_"
                android:onClick="nodeClick" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

第二步: 在Activity中實現功能(完整代碼)

package com.jerehedu.administrator.baidumapapplication;
import android.app.Activity;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfigeration;
import com.baidu.mapapi.model.LatLng;

import com.baidu.mapapi.overlayutil.DrivingRouteOvelray;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.TransitRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
public class RoutePlanDemo extends Activity implements BaiduMap.OnMapClickListener,
        OnGetRoutePlanResultListener {
    //瀏覽路線節點相關
    Button mBtnPre = null;//上一個節點
    Button mBtnNext = null;//下一個節點
    int nodeIndex = -1;//節點索引,供瀏覽節點時使用
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = false;
    private TextView popupText = null;

    //地圖相關,使用繼承MapView的MyRouteMapView目的是重寫touch事件實現泡泡處理
    //若是不處理touch事件,則無需繼承,直接使用MapView便可
    MapView mMapView = null;    // 地圖View
    BaiduMap mBaidumap = null;
    //搜索相關
    RoutePlanSearch mSearch = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_routeplan);
        CharSequence titleLable = "路線規劃功能";
        setTitle(titleLable);
        //初始化地圖
        mMapView = (MapView) findViewById(R.id.map);
        mBaidumap = mMapView.getMap();

        //設定中心點座標
        LatLng cenpt = new LatLng(37.52,121.39);
        //定義地圖狀態
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .build();
        //定義MapStatusUpdate對象,以便描述地圖狀態將要發生的變化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改變地圖狀態
        mBaidumap.setMapStatus(mMapStatusUpdate);
        mBtnPre = (Button) findViewById(R.id.pre);
        mBtnNext = (Button) findViewById(R.id.next);
        mBtnPre.setVisibility(View.INVISIBLE);
        mBtnNext.setVisibility(View.INVISIBLE);
        //地圖點擊事件處理
        mBaidumap.setOnMapClickListener(this);
        // 初始化搜索模塊,註冊事件監聽
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
    }

    /**
     * 發起路線規劃搜索示例
     *
     * @param v
     */
    public void SearchButtonProcess(View v) {
        //重置瀏覽節點的路線數據
        route = null;
        mBtnPre.setVisibility(View.INVISIBLE);
        mBtnNext.setVisibility(View.INVISIBLE);
        mBaidumap.clear();
        // 處理搜索按鈕響應
        EditText editSt = (EditText) findViewById(R.id.start);
        EditText editEn = (EditText) findViewById(R.id.end);
        //設置起終點信息,對於tranist search 來講,城市名無心義
        PlanNode stNode = PlanNode.withCityNameAndPlaceName("煙臺", editSt.getText().toString());
        PlanNode enNode = PlanNode.withCityNameAndPlaceName("煙臺", editEn.getText().toString());

        // 實際使用中請對起點終點城市進行正確的設定
        if (v.getId() == R.id.drive) {
            mSearch.drivingSearch((new DrivingRoutePlanOption())
                    .from(stNode)
                    .to(enNode));
        } else if (v.getId() == R.id.transit) {
            mSearch.transitSearch((new TransitRoutePlanOption())
                    .from(stNode)
                    .city("煙臺")
                    .to(enNode));
        } else if (v.getId() == R.id.walk) {
            mSearch.walkingSearch((new WalkingRoutePlanOption())
                    .from(stNode)
                    .to(enNode));
        }
    }

    /**
     * 節點瀏覽示例
     *
     * @param v
     */
    public void nodeClick(View v) {
        if (route == null ||
                route.getAllStep() == null) {
            return;
        }
        if (nodeIndex == -1 && v.getId() == R.id.pre) {
            return;
        }
        //設置節點索引
        if (v.getId() == R.id.next) {
            if (nodeIndex < route.getAllStep().size() - 1) {
                nodeIndex++;
            } else {
                return;
            }
        } else if (v.getId() == R.id.pre) {
            if (nodeIndex > 0) {
                nodeIndex--;
            } else {
                return;
            }
        }
        //獲取節結果信息
        LatLng nodeLocation = null;
        String nodeTitle = null;
        Object step = route.getAllStep().get(nodeIndex);
        if (step instanceof DrivingRouteLine.DrivingStep) {
            nodeLocation = ((DrivingRouteLine.DrivingStep) step).getEntrace().getLocation();
            nodeTitle = ((DrivingRouteLine.DrivingStep) step).getInstructions();
        } else if (step instanceof WalkingRouteLine.WalkingStep) {
            nodeLocation = ((WalkingRouteLine.WalkingStep) step).getEntrace().getLocation();
            nodeTitle = ((WalkingRouteLine.WalkingStep) step).getInstructions();
        } else if (step instanceof TransitRouteLine.TransitStep) {
            nodeLocation = ((TransitRouteLine.TransitStep) step).getEntrace().getLocation();
            nodeTitle = ((TransitRouteLine.TransitStep) step).getInstructions();
        }

        if (nodeLocation == null || nodeTitle == null) {
            return;
        }
        //移動節點至中心
        mBaidumap.setMapStatus(MapStatusUpdateFactory.newLatLng(nodeLocation));
        // show popup
        popupText = new TextView(RoutePlanDemo.this);
        popupText.setBackgroundResource(R.drawable.popup);
        popupText.setTextColor(0xFF000000);
        popupText.setText(nodeTitle);
        mBaidumap.showInfoWindow(new InfoWindow(popupText, nodeLocation,null));

    }

    /**
     * 切換路線圖標,刷新地圖使其生效
     * 注意: 起終點圖標使用中心對齊.
     */
    public void changeRouteIcon(View v) {
        if (routeOverlay == null) {
            return;
        }
        if (useDefaultIcon) {
            ((Button) v).setText("自定義起終點圖標");
            Toast.makeText(this,
                    "將使用系統起終點圖標",
                    Toast.LENGTH_SHORT).show();

        } else {
            ((Button) v).setText("系統起終點圖標");
            Toast.makeText(this,
                    "將使用自定義起終點圖標",
                    Toast.LENGTH_SHORT).show();

        }
        useDefaultIcon = !useDefaultIcon;
        routeOverlay.removeFromMap();
        routeOverlay.addToMap();
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(RoutePlanDemo.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起終點或途經點地址有岐義,經過如下接口獲取建議查詢信息
            //result.getSuggestAddrInfo()
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            mBtnPre.setVisibility(View.VISIBLE);
            mBtnNext.setVisibility(View.VISIBLE);
            route = result.getRouteLines().get(0);
            WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            routeOverlay = overlay;
            overlay.setData(result.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
        }

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult result) {

        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(RoutePlanDemo.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起終點或途經點地址有岐義,經過如下接口獲取建議查詢信息
            //result.getSuggestAddrInfo()
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            mBtnPre.setVisibility(View.VISIBLE);
            mBtnNext.setVisibility(View.VISIBLE);
            route = result.getRouteLines().get(0);
            TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            routeOverlay = overlay;
            overlay.setData(result.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
        }
    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(RoutePlanDemo.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起終點或途經點地址有岐義,經過如下接口獲取建議查詢信息
            //result.getSuggestAddrInfo()
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            mBtnPre.setVisibility(View.VISIBLE);
            mBtnNext.setVisibility(View.VISIBLE);
            route = result.getRouteLines().get(0);
            DrivingRouteOvelray overlay = new MyDrivingRouteOverlay(mBaidumap);
            routeOverlay = overlay;
            mBaidumap.setOnMarkerClickListener(overlay);
            overlay.setData(result.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
        }
    }

    //定製RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOvelray {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }

    private class MyWalkingRouteOverlay extends WalkingRouteOverlay {

        public MyWalkingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }

    private class MyTransitRouteOverlay extends TransitRouteOverlay {

        public MyTransitRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }

    @Override
    public void onMapClick(LatLng point) {
        mBaidumap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi poi) {
        return false;
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mSearch.destroy();
        mMapView.onDestroy();
        super.onDestroy();
    }
}

百度地圖的重要使用功能都已介紹完畢,但願你們在使用的時候有好的使用方法和效果時能夠一塊兒分享ui

 

做者:傑瑞教育
出處: http://www.cnblogs.com/jerehedu/ 
版權聲明:本文版權歸 傑瑞教育 技有限公司和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。
技術諮詢:JRedu技術交流
相關文章
相關標籤/搜索