Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 百度地圖集成實戰:路線規劃與導航

編輯:關於 Android 程式設計

關於百度地圖的導航功能曾困擾我很長一段時間,現在終於整理出來了,來給大家分享一下。其實並不難,把百度的 API 範例 Demo 下載下來,找到需要的部分即可。使用前當然要先申請百度帳戶並取得 KEY。

一、添加權限

按照官方說明先添加各項權限:

<!-- 用於進行網路定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用於訪問 GPS 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 用於訪問 wifi 網路資訊,wifi 資訊會用於網路定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 獲取運營商資訊,用於支持提供運營商資訊相關的接口 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 用於讀取手機目前的狀態 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 寫入擴展存儲,向擴展卡寫入數據,用於寫入離線定位數據 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 訪問網路,網路定位需要上網 -->
<uses-permission android:name="android.permission.INTERNET" />

清單檔中的其他配置:

<meta-data
    android:name="com.baidu.lbsapi.API_KEY"
    android:value="請輸入你的 key" />
<service android:enabled="true"
    android:name="com.baidu.location.f"
    android:process=":remote" />

別忘了建立並在清單檔中配置 Application,在使用 SDK 各組件之前先初始化 context:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // 在使用 SDK 各組件之前初始化 context 資訊,傳入 ApplicationContext
        SDKInitializer.initialize(this);
    }
}

從範例中找到程式入口類,這個類裡的內容基本就是我們需要的。它展示了如何進行駕車、步行、公車、騎行路線搜索,並在地圖上使用 RouteOverlay、TransitOverlay 繪製,同時演示節點瀏覽與彈出泡泡。

public class MainActivity extends Activity
        implements BaiduMap.OnMapClickListener, OnGetRoutePlanResultListener {

    private Button mBtnPre = null;   // 上一個節點
    private Button mBtnNext = null;  // 下一個節點
    private int nodeIndex = -1;      // 節點索引
    private RouteLine route = null;
    private OverlayManager routeOverlay = null;
    private boolean useDefaultIcon = false;
    private TextView popupText = null;

    private MapView mMapView = null;
    private BaiduMap mBaidumap = null;
    private RoutePlanSearch mSearch = null;
    private TransitRouteResult nowResult = null;
    private DrivingRouteResult nowResultd = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("路線規劃功能");
        mMapView = (MapView) findViewById(R.id.map);
        mBaidumap = mMapView.getMap();
        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);
    }

    /** 發起路線規劃搜索 */
    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);
        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));
        } else if (v.getId() == R.id.bike) {
            mSearch.bikingSearch(new BikingRoutePlanOption().from(stNode).to(enNode));
        }
    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(MainActivity.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            mBtnPre.setVisibility(View.VISIBLE);
            mBtnNext.setVisibility(View.VISIBLE);
            route = result.getRouteLines().get(0);
            DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            routeOverlay = overlay;
            overlay.setData(result.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
        }
    }

    // 其餘步行、公車、騎行結果回呼類似,這裡省略
    // 自訂起終點圖標
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {
        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;
        }
    }

    @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(); }
}

找到上面這個類就好辦了。此外還有與它關聯的一些類(如 RouteLineAdapter、路線選擇 Dialog 等),需要時一併從範例中複製過來即可。

主佈局 main.xml 包含起點、終點輸入框,以及駕車、公車、步行、騎行、自訂圖標、上一個/下一個節點等按鈕,並以 com.baidu.mapapi.map.MapView 作為地圖容器:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <TextView 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:text="龍澤" />
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <TextView 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:text="西單" />
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <Button android:id="@+id/drive" android:onClick="searchButtonProcess"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:layout_weight="1.0" android:text="駕車搜索" />
        <Button android:id="@+id/transit" android:onClick="searchButtonProcess"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:layout_weight="1.0" android:text="公交搜索" />
        <Button android:id="@+id/walk" android:onClick="searchButtonProcess"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:layout_weight="1.0" android:text="步行搜索" />
        <Button android:id="@+id/bike" android:onClick="searchButtonProcess"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:layout_weight="1.0" android:text="騎行搜索" />
    </LinearLayout>
    <RelativeLayout 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" />
    </RelativeLayout>
</LinearLayout>

完整實現後,使用者輸入起訖點、選擇出行方式,即可在地圖上繪製路線並支援逐節點瀏覽,還能自訂起終點圖標。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved