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

Android 百度地圖實戰:自訂公交換乘路線圖層

編輯:關於 Android 程式設計

百度地圖 SDK 內建的路線圖層樣式固定,很難符合產品設計稿。本文示範如何自行擴展 RouteOverlay 與 ItemizedOverlay,把公交換乘方案的每一段路徑、每一個關鍵點都畫成自訂樣式,並在檢索完成後自動把地圖動畫移動到起點。

一、需求描述

目標是:輸入城市與關鍵字,檢索該城市的公交換乘方案,並以自訂圖層呈現結果。

二、Application 類:初始化 BMapManager

百度地圖的 BMapManager 建議放在 Application 層建立,避免每個 Activity 重複初始化帶來的時間消耗。

 public class App extends Application { static App mDemoApp; // 百度 MapAPI 的管理類 public BMapManager mBMapMan = null; // 授權 Key,申請處:https://dev.baidu.com/wiki/static/imap/key/ public String mStrKey = "Your APPKey"; boolean m_bKeyRight = true; // 授權 Key 是否正確 // 通用事件監聽,用來處理網路錯誤、授權驗證失敗等 public static class MyGeneralListener implements MKGeneralListener { @Override public void onGetNetworkState(int iError) { Log.d("MyGeneralListener", "onGetNetworkState error is "+ iError); Toast.makeText(App.mDemoApp.getApplicationContext(), "您的網絡出錯啦!", Toast.LENGTH_LONG).show(); } @Override public void onGetPermissionState(int iError) { Log.d("MyGeneralListener", "onGetPermissionState error is "+ iError); if (iError == MKEvent.ERROR_PERMISSION_DENIED) { // 授權 Key 錯誤 Toast.makeText(App.mDemoApp.getApplicationContext(), "請輸入正確的授權Key!", Toast.LENGTH_LONG).show(); App.mDemoApp.m_bKeyRight = false; } } } @Override public void onCreate() { Log.v("BMapApiDemoApp", "onCreate"); mDemoApp = this; mBMapMan = new BMapManager(this); mBMapMan.init(this.mStrKey, new MyGeneralListener()); mBMapMan.getLocationManager().setNotifyInternal(10, 5); super.onCreate(); } @Override // App 結束前呼叫 destroy(),避免重複初始化 public void onTerminate() { if (mBMapMan != null) { mBMapMan.destroy(); mBMapMan = null; } super.onTerminate(); } } 

三、自訂路線圖層

CustomRouteOverLay 擴展 RouteOverlay:負責把公交換乘方案的線路與關鍵點畫在地圖上。RouteOverlay 本來同時服務開車、步行、公交三種方案,我們主要針對公交情境調整呈現。

CustomOverlayItem 擴展 ItemizedOverlay<OverlayItem>:覆蓋物的集合類,用來把具相同特性的座標以自訂圖示標記出來。每個 OverlayItem 對應一個座標點。

CustomRouteOverLay 程式碼

 public class CustomRouteOverLay extends RouteOverlay { public Activity ac; private MapView mapView; static ArrayList<View> overlayviews = new ArrayList<View>(); public CustomRouteOverLay(Activity arg0, MapView arg1) { super(arg0, arg1); ac = arg0; mapView = arg1; } @Override protected boolean onTap(int arg0) { return true; } @Override public void setData(MKRoute arg0) { super.setData(arg0); addHint(arg0); } public void addHints(MKRoute routes) { for (int i = 0; i < routes.getNumSteps(); i++) { Drawable marker = ac.getResources().getDrawable(R.drawable.pop); // 取得要標在地圖上的資源 marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); // 定義 marker 的位置與邊界 OverItemT overitem = new OverItemT(marker, ac, routes.getStep(i).getContent(), routes.getStep(i).getPoint()); mapView.getOverlays().add(overitem); } mapView.invalidate(); } /** 繪製路線指示 */ public void addHint(MKRoute routes) { mapView.getOverlays().clear();// 先清空 View mPopView = ac.getLayoutInflater().inflate(R.layout.popview, null); for(int i=0;i< overlayviews.size();i++){ mapView.removeViewInLayout(overlayviews.get(i)); overlayviews.remove(i); } mapView.invalidate(); // 逐一加入路線節點 for (int i = 0; i < routes.getNumSteps(); i++) { Drawable marker = ac.getResources().getDrawable(R.drawable.pop); marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); GeoPoint pt = routes.getStep(i).getPoint(); if (i != 0 && i != routes.getNumSteps() - 1) { mPopView = ac.getLayoutInflater().inflate(R.layout.popview, null); mapView.addView(mPopView, new MapView.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.TOP_LEFT)); mPopView.setVisibility(View.GONE); mapView.updateViewLayout(mPopView, new MapView.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pt, MapView.LayoutParams.BOTTOM_CENTER)); mPopView.setVisibility(View.VISIBLE); Button button = (Button) mPopView.findViewById(R.id.overlay_pop); button.setText(routes.getStep(i).getContent()); overlayviews.add(mPopView); overlayviews.add(button); } else { // 自訂起點與終點樣式 mPopView = ac.getLayoutInflater().inflate(R.layout.popview, null); mapView.addView(mPopView, new MapView.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.TOP_LEFT)); mPopView.setVisibility(View.GONE); mapView.updateViewLayout(mPopView, new MapView.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pt, MapView.LayoutParams.BOTTOM_CENTER)); mPopView.setVisibility(View.VISIBLE); Button button = (Button) mPopView.findViewById(R.id.overlay_pop); button.offsetTopAndBottom(100); button.setTextColor(Color.BLUE); button.setBackgroundColor(Color.TRANSPARENT); button.setText(routes.getStep(i).getContent()); overlayviews.add(mPopView); overlayviews.add(button); } } } class OverItemT extends ItemizedOverlay<OverlayItem> { private Drawable marker; private Context mContext; private GeoPoint p; private OverlayItem o; public OverItemT(Drawable marker, Context context, String title, GeoPoint p) { super(boundCenterBottom(marker)); this.marker = marker; this.mContext = context; this.p = p; // OverlayItem 的三個參數:位置、標題、描述 o = new OverlayItem(p, title, title); populate(); // 有了資料後,呼叫其他方法前必須先呼叫此方法 } public void updateOverlay() { populate(); } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { // Projection 負責螢幕像素座標與經緯度座標之間的轉換 Projection projection = mapView.getProjection(); for (int index = size() - 1; index >= 0; index--) { OverlayItem overLayItem = getItem(index); String title = overLayItem.getTitle(); // 經緯度轉為相對於 MapView 左上角的螢幕座標 Point point = projection.toPixels(overLayItem.getPoint(), null); Paint paintText = new Paint(); paintText.setColor(Color.BLUE); paintText.setTextSize(15); canvas.drawText(title, point.x - 30, point.y, paintText); } super.draw(canvas, mapView, shadow); // 調整邊界,使 (0,0) 落在 drawable 底部中心 boundCenterBottom(marker); } @Override protected OverlayItem createItem(int i) { return o; } @Override public int size() { return 1; } } }

CustomOverlayItem 程式碼

這個類較單純,用來標記單一座標並在點擊時彈出提示。

 public class CustomOverlayItem extends ItemizedOverlay<OverlayItem> { private Context mContext; private OverlayItem overlay; boolean showtext; private Drawable marker; public CustomOverlayItem(Drawable marker, Context context, GeoPoint p, String title, String sinppet, boolean showtext) { super(boundCenterBottom(marker)); this.mContext = context; // GeoPoint 的單位是微度(度 × 1E6) this.showtext = showtext; this.marker = marker; overlay = new OverlayItem(p, title, sinppet); populate(); } @Override protected OverlayItem createItem(int i) { return overlay; } @Override public int size() { return 1; } @Override public void draw(Canvas canvas, MapView mapView, boolean arg2) { super.draw(canvas, mapView, arg2); Projection projection = mapView.getProjection(); String title = overlay.getTitle(); Point point = projection.toPixels(overlay.getPoint(), null); Paint paintText = new Paint(); Paint paint = new Paint(); paint.setAlpha(255); paint.setColor(Color.DKGRAY); paint.setStrokeWidth(5); paintText.setColor(Color.BLUE); paintText.setTextSize(15); canvas.drawText(title, point.x - 30, point.y - 50, paintText); boundCenterBottom(marker); } @Override protected boolean onTap(int i) { if (showtext) Toast.makeText(this.mContext, overlay.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }

四、主程式 BuslineSearch

繼承 MapActivity,負責初始化地圖、發起檢索、把結果交給自訂圖層,並在 onGetBusDetailResult 回呼中把地圖動畫移到起點。

 public class BuslineSearch extends MapActivity { Button mBtnSearch = null; // 搜尋按鈕 MapView mMapView = null; // 地圖 View MKSearch mSearch = null; // 搜尋模組 String mCityName = null; LocationListener loc_listener; App app = null; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.buslinesearch); app = (App) this.getApplication(); if (app.mBMapMan == null) { app.mBMapMan = new BMapManager(getApplication()); app.mBMapMan.init(app.mStrKey, new App.MyGeneralListener()); } app.mBMapMan.start(); // 使用地圖 SDK 前必須先初始化 MapActivity super.initMapActivity(app.mBMapMan); mMapView = (MapView) findViewById(R.id.bmapView); mMapView.setBuiltInZoomControls(true); // 縮放動畫過程中也繪製 overlay mMapView.setDrawOverlayWhenZooming(true); // 初始化搜尋模組,註冊事件監聽 MapController mMapController = mMapView.getController(); // 取得 MapView 的控制權,可用來控制平移與縮放 GeoPoint point = new GeoPoint((int) (39.915 * 1E6), (int) (116.404 * 1E6)); // 單位是微度 mMapController.setCenter(point); // 設定地圖中心 mMapController.setZoom(15); // 設定 zoom 級別 mSearch = new MKSearch(); mSearch.init(app.mBMapMan, new MKSearchListener() { public void onGetPoiResult(MKPoiResult res, int type, int error) { // 錯誤碼可參考 MKEvent 的定義 if (error != 0 || res == null) { Toast.makeText(BuslineSearch.this, "抱歉,未找到結果", Toast.LENGTH_LONG).show(); return; } MKPoiInfo curPoi = null; int totalPoiNum = res.getNumPois(); for (int idx = 0; idx < totalPoiNum; idx++) { curPoi = res.getPoi(idx); if (2 == curPoi.ePoiType) { break; } } mSearch.busLineSearch(mCityName, curPoi.uid); } public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { } public void onGetTransitRouteResult(MKTransitRouteResult res, int error) { } public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { } public void onGetAddrResult(MKAddrInfo res, int error) { } public void onGetBusDetailResult(MKBusLineResult result, int iError) { if (iError != 0 || result == null) { Toast.makeText(BuslineSearch.this, "抱歉,未找到結果", Toast.LENGTH_LONG).show(); return; } CustomRouteOverLay routeOverlay = new CustomRouteOverLay(BuslineSearch.this, mMapView); routeOverlay.setData(result.getBusRoute()); mMapView.getOverlays().clear(); mMapView.getOverlays().add(routeOverlay); mMapView.invalidate(); // 動畫移動到起點 mMapView.getController().animateTo(result.getBusRoute().getStart()); } @Override public void onGetSuggestionResult(MKSuggestionResult res, int arg1) { } }); // 定位監聽 loc_listener = new LocationListener() { @Override public void onLocationChanged(Location location) { if (location != null) { Drawable marker = getResources().getDrawable(R.drawable.ic_launcher); final GeoPoint p = new GeoPoint( (int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)); CustomOverlayItem item = new CustomOverlayItem(marker, BuslineSearch.this, p, "我的位置", "", false); mMapView.getOverlays().add(item); mMapView.getController().animateTo(p); } } }; mBtnSearch = (Button) findViewById(R.id.search); mBtnSearch.setOnClickListener(new OnClickListener() { public void onClick(View v) { SearchButtonProcess(v); } }); } void SearchButtonProcess(View v) { if (mBtnSearch.equals(v)) { mMapView.getOverlays().clear(); mMapView.invalidate(); EditText editCity = (EditText) findViewById(R.id.city); EditText editSearchKey = (EditText) findViewById(R.id.searchkey); mCityName = editCity.getText().toString(); mSearch.poiSearchInCity(mCityName, editSearchKey.getText().toString()); } } @Override protected void onPause() { if (null == app) app = (App) this.getApplication(); app.mBMapMan.getLocationManager().removeUpdates(loc_listener); app.mBMapMan.stop(); super.onPause(); } @Override protected void onResume() { if (null == app) app = (App) this.getApplication(); app.mBMapMan.start(); super.onResume(); app.mBMapMan.getLocationManager().requestLocationUpdates(loc_listener); } @Override protected boolean isRouteDisplayed() { return false; } }

關鍵觀念整理

GeoPoint 的單位是微度。經緯度必須乘以 1E6 才能建構 GeoPoint,這是新手最常踩的坑之一,忘記轉換會導致地圖定位到非洲外海。

populate() 必須先呼叫。ItemizedOverlay 在 getCount()、getItem() 等方法被呼叫前,必須先 populate() 完成內部資料準備,否則會拿到空集合。

boundCenterBottom() 決定錨點。這個靜態方法把 drawable 的 (0,0) 對齊到底部中央,讓圖示看起來是「立」在座標上,而不是被座標壓在中間。

Projection 是座標系轉換的橋樑。toPixels() 把經緯度換成螢幕像素,是所有自繪覆蓋物的基礎。要在地圖上畫任何自訂內容,都繞不開它。

生命週期要成對處理。onResume 啟動 BMapManager 並註冊定位、onPause 停止並移除監聽,這組搭配能避免背景耗電與記憶體洩漏。

版本提醒

本文示範的是百度地圖 Android SDK 的舊版 API(BMapManager、MapActivity、MKSearch、GeoPoint)。現行版本已全面改為 MapFragment 搭配 SearchManager 與 LatLng,上述類別多已不再提供。若要在新專案實作類似效果,建議對照官方最新文件的 Overlay 客製化章節,整體思路——擴展 Overlay、在 draw 中用 Projection 轉換座標、以 ItemizedOverlay 管理多個標記——則延續不變。

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