編輯:關於 Android 開發
本範例的目標,是基於百度地圖 API,檢索指定城市、指定公交流線的交通路線,並將路線與關鍵節點以自訂樣式呈現在地圖上,效果如下圖所示。

首先建立一個繼承自 Application 的 App 類,負責建立並初始化百度地圖的管理器 BMapManager,同時處理授權驗證與網路錯誤等通用事件。
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的退出之前調用mapadpi的destroy()函數,避免重復初始化帶來的時間消耗
public void onTerminate() {
if (mBMapMan != null) {
mBMapMan.destroy();
mBMapMan = null;
}
super.onTerminate();
}
}
三、自訂公交路線圖層與圖標標識
核心在於兩個自訂類別:CustomRouteOverLay 繼承自 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());
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;
o = new OverlayItem(p, title, title);
populate();
}
public void updateOverlay() { populate(); }
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Projection projection = mapView.getProjection();
for (int index = size() - 1; index >= 0; index--) {
OverlayItem overLayItem = getItem(index);
String title = overLayItem.getTitle();
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);
boundCenterBottom(marker);
}
@Override
protected OverlayItem createItem(int i) { return o; }
@Override
public int size() { return 1; }
@Override
protected boolean onTap(int i) { return true; }
@Override
public boolean onTap(GeoPoint arg0, MapView arg1) { return super.onTap(arg0, arg1); }
}
}
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;
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 的主程式 BuslineSearch,完成地圖初始化、搜尋模組註冊、定位監聽與路線繪製等一連串工作。
public class BuslineSearch extends MapActivity {
Button mBtnSearch = null;
MapView mMapView = null;
MKSearch 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();
super.initMapActivity(app.mBMapMan);
mMapView = (MapView) findViewById(R.id.bmapView);
mMapView.setBuiltInZoomControls(true);
mMapView.setDrawOverlayWhenZooming(true);
mMapView.setBuiltInZoomControls(true);
MapController mMapController = mMapView.getController();
GeoPoint point = new GeoPoint((int) (39.915 * 1E6), (int) (116.404 * 1E6));
mMapController.setCenter(point);
mMapController.setZoom(15);
mSearch = new MKSearch();
mSearch.init(app.mBMapMan, new MKSearchListener() {
public void onGetPoiResult(MKPoiResult res, int type, int error) {
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) { 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;
}
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) {
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());
}
}
@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; }
@Override protected void onDestroy() { super.onDestroy(); }
}
作者:傑瑞教育
出處:https://www.cnblogs.com/jerehedu/
版權聲明:本文版權歸煙台傑瑞教育科技有限公司和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

Remote Displayer for Android V1.0:遠端手機畫面顯示工具
Remote Displayer for Android V1.0 功能說明 這款工具主要用於在電腦端遠端查看 Android 裝置畫面,並可進行螢幕擷取。使用時,電腦
百度地圖開發學習(二):地圖定位功能全流程解析
百度地圖開發學習(二):地圖定位功能全流程解析 定位是地圖開發中不可迴避的重要環節,而我也在學習的道路上不斷摸索。以下整理一下自己對百度定位 SDK 的理解與實踐。 一、
Android 大雜燴工程之 ListView 開發(二)與數據倉庫設計模式
Android 大雜燴工程之 ListView 開發(二)與數據倉庫設計模式 今天是放完假後工作的第一天,為了證明我不是一段幽靈代碼,先給各位看客老爺們道聲:祝大家節日
Android 自學筆記(Android Studio)4.4:AdapterView 家族與 Adapter 機制詳解
一、引言 AdapterView 是個抽象類別,它派生出來的眾多子類在用法上大同小異,差別主要在呈現形式,因此常被歸在同一個單元來學習。理解它的關鍵在於一個觀念:Adap