Android百度地圖自訂大眾運輸路線導航_Android

來源:互聯網
上載者:User

一、問題描述

基於百度地圖實現檢索指定城市指定公交的交通路線圖,效果如圖所示

二、萬用群組件Application類,主要建立並初始化BMapManager

public class App extends Application {static App mDemoApp;//百度MapAPI的管理類public BMapManager mBMapMan = null;// 授權Key// 申請地址:http://dev.baidu.com/wiki/static/imap/key/public String mStrKey = "Your APPKey";boolean m_bKeyRight = true; // 授權Key正確,驗證通過// 常用事件監聽,用來處理通常的網路錯誤,授權驗證錯誤等public static class MyGeneralListener implements MKGeneralListener {@Overridepublic void onGetNetworkState(int iError) {Log.d("MyGeneralListener", "onGetNetworkState error is "+ iError);Toast.makeText(App.mDemoApp.getApplicationContext(), "您的網路出錯啦!",Toast.LENGTH_LONG).show();}@Overridepublic 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;}}}@Overridepublic 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的退出之前調用mapadpi的destroy()函數,避免重複初始化帶來的時間消耗public void onTerminate() {if (mBMapMan != null) {mBMapMan.destroy();mBMapMan = null;}super.onTerminate();}} 

三、編寫公交的路線圖層(CustomRouteOverLay)和表徵圖標識(CustomOverlayItem)

CustomRouteOverLay組件擴充RouteOverlay:

主要公交、步行和駕車線路圖層,將公交、步行和駕車出行方案的路線及關鍵點顯示在地圖上,根據車輛路線的起點和終點進行駕車路線的檢索;

CustomOverlayItem擴充ItemizedOverlay<OverlayItem>:

覆蓋物的集合類,使用這個類可以將地圖上具有相同屬性或者特性的座標使用表徵圖標識出來,OverLayItem 這個類對象則是ItemizedOverLay中一個一個的Item對象 也就是每個座標組應的覆蓋物

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;// TODO Auto-generated constructor stub}@Overrideprotected boolean onTap(int arg0) {// TODO Auto-generated method stub// return super.onTap(arg0);return true;}@Overridepublic void setData(MKRoute arg0) {// TODO Auto-generated method stubsuper.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()); // 為maker定義位置和邊界OverItemT overitem = new OverItemT(marker,ac, routes.getStep(i).getContent(),routes.getStep(i).getPoint());// OverlayItem over=new OverlayItem(routes.GET, null, null);mapView.getOverlays().add(overitem); // 添加ItemizedOverlay執行個體到mMapView}mapView.invalidate();}/*** 增加 指示路線* @param routes*/public void addHint(MKRoute routes) {mapView.getOverlays().clear();// 先清空// mapView.removeAllViewsInLayout();View mPopView = ac.getLayoutInflater().inflate(R.layout.popview,null);for(int i=0;i< overlayviews.size();i++){System.out.println("remove &"+i);mapView.removeViewInLayout(overlayviews.get(i));overlayviews.remove(i);}mapView.invalidate();// 添加ItemizedOverlayfor (int i = 0; i < routes.getNumSteps(); i++) {Drawable marker = ac.getResources().getDrawable(R.drawable.pop); // 得到需要標在地圖上的資源marker.setBounds(0, 0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight()); // 為maker定義位置和邊界GeoPoint pt = routes.getStep(i).getPoint();// =// routes.get(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的三個參數依次為:item的位置,標題文本,文字片段o = new OverlayItem(p, title, title);populate(); // createItem(int)方法構造item。一旦有了資料,在調用其它方法前,首先調用這個方法}public void updateOverlay() {populate();}@Overridepublic void draw(Canvas canvas, MapView mapView, boolean shadow) {// Projection介面用於螢幕像素座標和經緯度座標之間的變換Projection projection = mapView.getProjection();for (int index = size() - 1; index >= 0; index--) { // 遍曆mGeoListOverlayItem overLayItem = getItem(index); // 得到給定索引的itemString 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);// 調整一個drawable邊界,使得(0,0)是這個drawable底部最後一行中心的一個像素boundCenterBottom(marker);}@Overrideprotected OverlayItem createItem(int i) {// TODO Auto-generated method stubreturn o;}@Overridepublic int size() {// TODO Auto-generated method stubreturn 1;}@Override// 處理當點擊事件protected boolean onTap(int i) {// 更新氣泡位置,並使之顯示return true;}@Overridepublic boolean onTap(GeoPoint arg0, MapView arg1) {// TODO Auto-generated method stub// 消去彈出的氣泡// ItemizedOverlayDemo.mPopView.setVisibility(View.GONE);return super.onTap(arg0, arg1);}}}

CustomOverlayItem代碼:

public class CustomOverlayItem extends ItemizedOverlay<OverlayItem> {// private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();private Context mContext;private OverlayItem overlay;boolean showtext;// private String title;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)// point = p;this.showtext = showtext;// this.title = title;this.marker = marker;overlay = new OverlayItem(p, title, sinppet);populate(); // createItem(int)方法構造item。一旦有了資料,在調用其它方法前,首先調用這個方法}@Overrideprotected OverlayItem createItem(int i) {return overlay;}@Overridepublic int size() {return 1;}@Overridepublic void draw(Canvas canvas, MapView mapView, boolean arg2) {// TODO Auto-generated method stubsuper.draw(canvas, mapView, arg2);// Projection介面用於螢幕像素座標和經緯度座標之間的變換Projection projection = mapView.getProjection();String title = overlay.getTitle();// 把經緯度變換到相對於MapView左上方的螢幕像素座標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.drawCircle(point.x, point.y, 100, paint);canvas.drawText(title, point.x-30, point.y-50, paintText); // 繪製文本// 調整一個drawable邊界,使得(0,0)是這個drawable底部最後一行中心的一個像素boundCenterBottom(marker);}@Override// 處理當點擊事件protected boolean onTap(int i) {if (showtext)Toast.makeText(this.mContext, overlay.getTitle(), Toast.LENGTH_SHORT).show();return true;}}

四、編寫主程式BuslineSearch,擴充MapActivity,實現地圖資訊的顯示

public class BuslineSearch extends MapActivity {Button mBtnSearch = null; // 搜尋按鈕MapView mMapView = null; // 地圖ViewMKSearch mSearch = null; // 搜尋模組,也可去掉地圖模組獨立使用String mCityName = null;LocationListener loc_listener;App app = null;static boolean flag = false;static Thread thread;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,請初始化地圖Activitysuper.initMapActivity(app.mBMapMan);mMapView = (MapView) findViewById(R.id.bmapView);mMapView.setBuiltInZoomControls(true);// 設定在縮放動畫過程中也顯示overlay,預設為不繪製mMapView.setDrawOverlayWhenZooming(true);mMapView.setBuiltInZoomControls(true);// 初始化搜尋模組,註冊事件監聽MapController mMapController = mMapView.getController(); // 得到mMapView的控制權,可以用它控制和驅動平移和縮放GeoPoint point = new GeoPoint((int) (39.915 * 1E6),(int) (116.404 * 1E6)); // 用給定的經緯度構造一個GeoPoint,單位是微度 (度 * 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;}// System.out.println(res.toString());// 找到大眾運輸路線poi nodeMKPoiInfo curPoi = null;int totalPoiNum = res.getNumPois();for (int idx = 0; idx < totalPoiNum; idx++) {Log.d("busline", "the busline is " + 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) {res.getPlan(0).getDistance();}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;}// result.getBusRoute().get// result.getBusRoute().getStart().toString();CustomRouteOverLay routeOverlay = new CustomRouteOverLay(BuslineSearch.this, mMapView);routeOverlay.setData(result.getBusRoute());mMapView.getOverlays().clear();System.out.println(mMapView.getOverlays().size());mMapView.getOverlays().add(routeOverlay);mMapView.invalidate();mMapView.getController().animateTo(result.getBusRoute().getStart());}@Overridepublic void onGetSuggestionResult(MKSuggestionResult res, int arg1) {// TODO Auto-generated method stub}});// mLocationManager.requestLocationUpdates(listener);// 註冊定位事件loc_listener = new LocationListener() {@Overridepublic void onLocationChanged(Location location) {if (location != null) {String strLog = String.format("您當前的位置:\r\n" + "緯度:%f\r\n"+ "經度:%f", location.getLongitude(),location.getLatitude());flag = true;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);OnClickListener clickListener = new OnClickListener() {public void onClick(View v) {SearchButtonProcess(v);}};mBtnSearch.setOnClickListener(clickListener);}void SearchButtonProcess(View v) {if (mBtnSearch.equals(v)) {mMapView.getOverlays().clear();mMapView.getOverlays().removeAll(mMapView.getOverlays());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());}}@Overrideprotected void onPause() {if (null == app)app = (App) this.getApplication();app.mBMapMan.getLocationManager().removeUpdates(loc_listener);app.mBMapMan.stop();super.onPause();}@Overrideprotected void onResume() {if (null == app)app = (App) this.getApplication();app.mBMapMan.start();super.onResume();app.mBMapMan.getLocationManager().requestLocationUpdates(loc_listener);// 定位}@Overrideprotected boolean isRouteDisplayed() {// TODO Auto-generated method stubreturn false;}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();}}

以上代碼內容是針對Android百度地圖自訂大眾運輸路線導航的相關知識,希望對大家有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.