天天看點

百度地圖之路線規劃

随時随地閱讀更多技術實戰幹貨,擷取項目源碼、學習資料,請關注源代碼社群公衆号(ydmsq666)、QQ技術交流群(183198395)。

百度地圖之路線規劃
百度地圖之路線規劃
百度地圖之路線規劃

在前面的一篇文章中介紹過查詢公交路線,不過那是根據公交路線的編号進行查詢,而且也隻是按公交搜尋,在本文中,将介紹根據起終點按駕車、公交、步行三種方式進行搜尋,功能更為強大,而且同樣可以浏覽節點,不過百度Demo提供的示例隻能在北京市進行搜尋,如果要在其他地方進行搜尋需要更改源代碼,初始化為其他城市,這裡,我将起終點城市也在界面上來進行擷取,使用起來就更加友善了,代碼如下:

主Activity(RoutePlanActivity):

package com.home;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.map.MKMapTouchListener;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.map.TransitOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKCityListInfo;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKRoute;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;

/**
 * 此demo用來展示如何進行駕車、步行、公交路線搜尋并在地圖使用RouteOverlay、TransitOverlay繪制
 * 同時展示如何進行節點浏覽并彈出泡泡
 * 
 */
public class RoutePlanActivity extends Activity {

	// UI相關
	Button mBtnDrive = null; // 駕車搜尋
	Button mBtnTransit = null; // 公交搜尋
	Button mBtnWalk = null; // 步行搜尋
	Button mBtnCusRoute = null; // 自定義路線
	Button mBtnCusIcon = null; // 自定義起終點圖示
	EditText startCityText;
	EditText endCityText;

	// 浏覽路線節點相關
	Button mBtnPre = null;// 上一個節點
	Button mBtnNext = null;// 下一個節點
	int nodeIndex = -2;// 節點索引,供浏覽節點時使用
	MKRoute route = null;// 儲存駕車/步行路線資料的變量,供浏覽節點時使用
	TransitOverlay transitOverlay = null;// 儲存公交路線圖層資料的變量,供浏覽節點時使用
	RouteOverlay routeOverlay = null;
	boolean useDefaultIcon = false;
	int searchType = -1;// 記錄搜尋的類型,區分駕車/步行和公交
	private PopupOverlay pop = null;// 彈出泡泡圖層,浏覽節點時使用
	private TextView popupText = null;// 泡泡view
	private View viewCache = null;

	// 地圖相關,使用繼承MapView的MyRouteMapView目的是重寫touch事件實作泡泡處理
	// 如果不處理touch事件,則無需繼承,直接使用MapView即可
	MapView mMapView = null; // 地圖View
	// 搜尋相關
	MKSearch mSearch = null; // 搜尋子產品,也可去掉地圖子產品獨立使用

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DemoApplication app = (DemoApplication) this.getApplication();
		setContentView(R.layout.activity_routeplan);
		CharSequence titleLable = "路線規劃功能";
		setTitle(titleLable);
		// 初始化地圖
		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.setBuiltInZoomControls(false);
		mMapView.getController().setZoom(12);
		mMapView.getController().enableClick(true);

		// UI初始化
		mBtnDrive = (Button) findViewById(R.id.drive);
		mBtnTransit = (Button) findViewById(R.id.transit);
		mBtnWalk = (Button) findViewById(R.id.walk);
		mBtnPre = (Button) findViewById(R.id.pre);
		mBtnNext = (Button) findViewById(R.id.next);
		mBtnCusRoute = (Button) findViewById(R.id.custombutton);
		mBtnCusIcon = (Button) findViewById(R.id.customicon);
		mBtnPre.setVisibility(View.INVISIBLE);
		mBtnNext.setVisibility(View.INVISIBLE);
		startCityText = (EditText) findViewById(R.id.activity_editText_startcity);
		endCityText = (EditText) findViewById(R.id.activity_editText_endcity);

		// 按鍵點選事件
		OnClickListener clickListener = new OnClickListener() {
			public void onClick(View v) {
				// 發起搜尋
				SearchButtonProcess(v);
			}
		};
		OnClickListener nodeClickListener = new OnClickListener() {
			public void onClick(View v) {
				// 浏覽路線節點
				nodeClick(v);
			}
		};
		OnClickListener customClickListener = new OnClickListener() {
			public void onClick(View v) {
				// 自設路線繪制示例
				intentToActivity();

			}
		};

		OnClickListener changeRouteIconListener = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				changeRouteIcon();
			}

		};

		mBtnDrive.setOnClickListener(clickListener);
		mBtnTransit.setOnClickListener(clickListener);
		mBtnWalk.setOnClickListener(clickListener);
		mBtnPre.setOnClickListener(nodeClickListener);
		mBtnNext.setOnClickListener(nodeClickListener);
		mBtnCusRoute.setOnClickListener(customClickListener);
		mBtnCusIcon.setOnClickListener(changeRouteIconListener);
		// 建立 彈出泡泡圖層
		createPaopao();

		// 地圖點選事件處理
		mMapView.regMapTouchListner(new MKMapTouchListener() {

			@Override
			public void onMapClick(GeoPoint point) {
				// 在此處理地圖點選事件
				// 消隐pop
				if (pop != null) {
					pop.hidePop();
				}
			}

			@Override
			public void onMapDoubleClick(GeoPoint point) {

			}

			@Override
			public void onMapLongClick(GeoPoint point) {

			}

		});
		// 初始化搜尋子產品,注冊事件監聽
		mSearch = new MKSearch();
		mSearch.init(app.mBMapManager, new MKSearchListener() {

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
				// 起點或終點有歧義,需要選擇具體的城市清單或位址清單
				if (error == MKEvent.ERROR_ROUTE_ADDR) {
					// 周遊所有位址
					ArrayList<MKPoiInfo> stPois = res.getAddrResult().mStartPoiList;
					ArrayList<MKPoiInfo> enPois = res.getAddrResult().mEndPoiList;
					ArrayList<MKCityListInfo> stCities = res.getAddrResult().mStartCityList;
					ArrayList<MKCityListInfo> enCities = res.getAddrResult().mEndCityList;
					return;
				}
				// 錯誤号可參考MKEvent中的定義
				if (error != 0 || res == null) {
					Toast.makeText(RoutePlanActivity.this, "抱歉,未找到結果",
							Toast.LENGTH_SHORT).show();
					return;
				}

				searchType = 0;
				routeOverlay = new RouteOverlay(RoutePlanActivity.this,
						mMapView);
				// 此處僅展示一個方案作為示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				// 清除其他圖層
				mMapView.getOverlays().clear();
				// 添加路線圖層
				mMapView.getOverlays().add(routeOverlay);
				// 執行重新整理使生效
				mMapView.refresh();
				// 使用zoomToSpan()綻放地圖,使路線能完全顯示在地圖上
				mMapView.getController().zoomToSpan(
						routeOverlay.getLatSpanE6(),
						routeOverlay.getLonSpanE6());
				// 移動地圖到起點
				mMapView.getController().animateTo(res.getStart().pt);
				// 将路線資料儲存給全局變量
				route = res.getPlan(0).getRoute(0);
				// 重置路線節點索引,節點浏覽時使用
				nodeIndex = -1;
				mBtnPre.setVisibility(View.VISIBLE);
				mBtnNext.setVisibility(View.VISIBLE);
			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
				// 起點或終點有歧義,需要選擇具體的城市清單或位址清單
				if (error == MKEvent.ERROR_ROUTE_ADDR) {
					// 周遊所有位址
					ArrayList<MKPoiInfo> stPois = res.getAddrResult().mStartPoiList;
					ArrayList<MKPoiInfo> enPois = res.getAddrResult().mEndPoiList;
					ArrayList<MKCityListInfo> stCities = res.getAddrResult().mStartCityList;
					ArrayList<MKCityListInfo> enCities = res.getAddrResult().mEndCityList;
					return;
				}
				if (error != 0 || res == null) {
					Toast.makeText(RoutePlanActivity.this, "抱歉,未找到結果",
							Toast.LENGTH_SHORT).show();
					return;
				}

				searchType = 1;
				transitOverlay = new TransitOverlay(RoutePlanActivity.this,
						mMapView);
				// 此處僅展示一個方案作為示例
				transitOverlay.setData(res.getPlan(0));
				// 清除其他圖層
				mMapView.getOverlays().clear();
				// 添加路線圖層
				mMapView.getOverlays().add(transitOverlay);
				// 執行重新整理使生效
				mMapView.refresh();
				// 使用zoomToSpan()綻放地圖,使路線能完全顯示在地圖上
				mMapView.getController().zoomToSpan(
						transitOverlay.getLatSpanE6(),
						transitOverlay.getLonSpanE6());
				// 移動地圖到起點
				mMapView.getController().animateTo(res.getStart().pt);
				// 重置路線節點索引,節點浏覽時使用
				nodeIndex = 0;
				mBtnPre.setVisibility(View.VISIBLE);
				mBtnNext.setVisibility(View.VISIBLE);
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
				// 起點或終點有歧義,需要選擇具體的城市清單或位址清單
				if (error == MKEvent.ERROR_ROUTE_ADDR) {
					// 周遊所有位址
					ArrayList<MKPoiInfo> stPois = res.getAddrResult().mStartPoiList;
					ArrayList<MKPoiInfo> enPois = res.getAddrResult().mEndPoiList;
					ArrayList<MKCityListInfo> stCities = res.getAddrResult().mStartCityList;
					ArrayList<MKCityListInfo> enCities = res.getAddrResult().mEndCityList;
					return;
				}
				if (error != 0 || res == null) {
					Toast.makeText(RoutePlanActivity.this, "抱歉,未找到結果",
							Toast.LENGTH_SHORT).show();
					return;
				}

				searchType = 2;
				routeOverlay = new RouteOverlay(RoutePlanActivity.this,
						mMapView);
				// 此處僅展示一個方案作為示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				// 清除其他圖層
				mMapView.getOverlays().clear();
				// 添加路線圖層
				mMapView.getOverlays().add(routeOverlay);
				// 執行重新整理使生效
				mMapView.refresh();
				// 使用zoomToSpan()綻放地圖,使路線能完全顯示在地圖上
				mMapView.getController().zoomToSpan(
						routeOverlay.getLatSpanE6(),
						routeOverlay.getLonSpanE6());
				// 移動地圖到起點
				mMapView.getController().animateTo(res.getStart().pt);
				// 将路線資料儲存給全局變量
				route = res.getPlan(0).getRoute(0);
				// 重置路線節點索引,節點浏覽時使用
				nodeIndex = -1;
				mBtnPre.setVisibility(View.VISIBLE);
				mBtnNext.setVisibility(View.VISIBLE);

			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
			}

			public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) {
			}

			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
			}

			@Override
			public void onGetPoiDetailSearchResult(int type, int iError) {
			}

			@Override
			public void onGetShareUrlResult(MKShareUrlResult result, int type,
					int error) {
			}
		});
	}

	/**
	 * 發起路線規劃搜尋示例
	 * 
	 * @param v
	 */
	void SearchButtonProcess(View v) {
		// 重置浏覽節點的路線資料
		route = null;
		routeOverlay = null;
		transitOverlay = null;
		mBtnPre.setVisibility(View.INVISIBLE);
		mBtnNext.setVisibility(View.INVISIBLE);
		// 處理搜尋按鈕響應
		EditText editSt = (EditText) findViewById(R.id.start);
		EditText editEn = (EditText) findViewById(R.id.end);

		// 對起點終點的name進行指派,也可以直接對坐标指派,指派坐标則将根據坐标進行搜尋
		MKPlanNode stNode = new MKPlanNode();
		stNode.name = editSt.getText().toString();
		MKPlanNode enNode = new MKPlanNode();
		enNode.name = editEn.getText().toString();
		String startCity = startCityText.getText().toString();
		String endCity = endCityText.getText().toString();
		if ("".equals(startCity)) {
			Toast.makeText(this, "請輸入起點城市", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!mBtnTransit.equals(v)) {
			if ("".equals(endCity)) {
				Toast.makeText(this, "請輸入終點城市", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		if (mBtnDrive.equals(v)) {
			mSearch.drivingSearch(startCity, stNode, endCity, enNode);
		} else if (mBtnTransit.equals(v)) {
			mSearch.transitSearch(startCity, stNode, enNode);
		} else if (mBtnWalk.equals(v)) {
			mSearch.walkingSearch(startCity, stNode, endCity, enNode);
		}
	}

	/**
	 * 節點浏覽示例
	 * 
	 * @param v
	 */
	public void nodeClick(View v) {
		viewCache = getLayoutInflater()
				.inflate(R.layout.custom_text_view, null);
		popupText = (TextView) viewCache.findViewById(R.id.textcache);
		if (searchType == 0 || searchType == 2) {
			// 駕車、步行使用的資料結構相同,是以類型為駕車或步行,節點浏覽方法相同
			if (nodeIndex < -1 || route == null
					|| nodeIndex >= route.getNumSteps())
				return;

			// 上一個節點
			if (mBtnPre.equals(v) && nodeIndex > 0) {
				// 索引減
				nodeIndex--;
				// 移動到指定索引的坐标
				mMapView.getController().animateTo(
						route.getStep(nodeIndex).getPoint());
				// 彈出泡泡
				popupText.setBackgroundResource(R.drawable.popup);
				popupText.setText(route.getStep(nodeIndex).getContent());
				pop.showPopup(BMapUtil.getBitmapFromView(popupText), route
						.getStep(nodeIndex).getPoint(), 5);
			}
			// 下一個節點
			if (mBtnNext.equals(v) && nodeIndex < (route.getNumSteps() - 1)) {
				// 索引加
				nodeIndex++;
				// 移動到指定索引的坐标
				mMapView.getController().animateTo(
						route.getStep(nodeIndex).getPoint());
				// 彈出泡泡
				popupText.setBackgroundResource(R.drawable.popup);
				popupText.setText(route.getStep(nodeIndex).getContent());
				pop.showPopup(BMapUtil.getBitmapFromView(popupText), route
						.getStep(nodeIndex).getPoint(), 5);
			}
		}
		if (searchType == 1) {
			// 公交換乘使用的資料結構與其他不同,是以單獨處理節點浏覽
			if (nodeIndex < -1 || transitOverlay == null
					|| nodeIndex >= transitOverlay.getAllItem().size())
				return;

			// 上一個節點
			if (mBtnPre.equals(v) && nodeIndex > 1) {
				// 索引減
				nodeIndex--;
				// 移動到指定索引的坐标
				mMapView.getController().animateTo(
						transitOverlay.getItem(nodeIndex).getPoint());
				// 彈出泡泡
				popupText.setBackgroundResource(R.drawable.popup);
				popupText.setText(transitOverlay.getItem(nodeIndex).getTitle());
				pop.showPopup(BMapUtil.getBitmapFromView(popupText),
						transitOverlay.getItem(nodeIndex).getPoint(), 5);
			}
			// 下一個節點
			if (mBtnNext.equals(v)
					&& nodeIndex < (transitOverlay.getAllItem().size() - 2)) {
				// 索引加
				nodeIndex++;
				// 移動到指定索引的坐标
				mMapView.getController().animateTo(
						transitOverlay.getItem(nodeIndex).getPoint());
				// 彈出泡泡
				popupText.setBackgroundResource(R.drawable.popup);
				popupText.setText(transitOverlay.getItem(nodeIndex).getTitle());
				pop.showPopup(BMapUtil.getBitmapFromView(popupText),
						transitOverlay.getItem(nodeIndex).getPoint(), 5);
			}
		}

	}

	/**
	 * 建立彈出泡泡圖層
	 */
	public void createPaopao() {

		// 泡泡點選響應回調
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				Log.v("click", "clickapoapo");
			}
		};
		pop = new PopupOverlay(mMapView, popListener);
	}

	/**
	 * 跳轉自設路線Activity
	 */
	public void intentToActivity() {
		// 跳轉到自設路線示範demo
		Intent intent = new Intent(this, CustomRouteOverlayActivity.class);
		startActivity(intent);
	}

	/**
	 * 切換路線圖示,重新整理地圖使其生效 注意: 起終點圖示使用中心對齊.
	 */
	protected void changeRouteIcon() {
		Button btn = (Button) findViewById(R.id.customicon);
		if (routeOverlay == null && transitOverlay == null) {
			return;
		}
		if (useDefaultIcon) {
			if (routeOverlay != null) {
				routeOverlay.setStMarker(null);
				routeOverlay.setEnMarker(null);
			}
			if (transitOverlay != null) {
				transitOverlay.setStMarker(null);
				transitOverlay.setEnMarker(null);
			}
			btn.setText("自定義起終點圖示");
			Toast.makeText(this, "将使用系統起終點圖示", Toast.LENGTH_SHORT).show();
		} else {
			if (routeOverlay != null) {
				routeOverlay.setStMarker(getResources().getDrawable(
						R.drawable.icon_st));
				routeOverlay.setEnMarker(getResources().getDrawable(
						R.drawable.icon_en));
			}
			if (transitOverlay != null) {
				transitOverlay.setStMarker(getResources().getDrawable(
						R.drawable.icon_st));
				transitOverlay.setEnMarker(getResources().getDrawable(
						R.drawable.icon_en));
			}
			btn.setText("系統起終點圖示");
			Toast.makeText(this, "将使用自定義起終點圖示", Toast.LENGTH_SHORT).show();
		}
		useDefaultIcon = !useDefaultIcon;
		mMapView.refresh();

	}

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

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

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

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

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

布局檔案(activity_routeplan):

<?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
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView_startcity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="起點城市:" />

        <EditText
            android:id="@+id/activity_editText_startcity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:text="北京" >

            <requestFocus />
        </EditText>

        <TextView
            android:id="@+id/textView_endcity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:text="終點城市:" />

        <EditText
            android:id="@+id/activity_editText_endcity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:text="北京" >

            <requestFocus />
        </EditText>
    </LinearLayout>

    <LinearLayout
        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
        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
        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:background="@drawable/button_style"
            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:background="@drawable/button_style"
            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:background="@drawable/button_style"
            android:text="步行搜尋" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <com.baidu.mapapi.map.MapView
            android:id="@+id/bmapView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:clickable="true" />

        <LinearLayout
            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/custombutton"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1.0"
                android:background="@drawable/button_style"
                android:text="自設路線示例" />

            <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:background="@drawable/button_style"
                android:text="自定義起終點圖示" />
        </LinearLayout>

        <LinearLayout
            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_" />

            <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_" />
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>
           

自設路線類(CustomRouteOverlayActivity)

package com.home;

import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.search.MKRoute;
import com.baidu.platform.comapi.basestruct.GeoPoint;

import android.app.Activity;
import android.os.Bundle;

/**
 * 此demo用來展示如何用自己的資料構造一條路線在地圖上繪制出來
 * 
 */
public class CustomRouteOverlayActivity extends Activity {

	// 地圖相關
	MapView mMapView = null; // 地圖View

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customroute);
		CharSequence titleLable = "路線規劃功能——自設路線示例";
		setTitle(titleLable);
		// 初始化地圖
		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.getController().enableClick(true);
		mMapView.getController().setZoom(13);

		/**
		 * 示範自定義路線使用方法 在北京地圖上畫一個北鬥七星
		 * 想知道某個點的百度經緯度坐标請點選:http://api.map.baidu.com/lbsapi/getpoint/index.html
		 */
		GeoPoint p1 = new GeoPoint((int) (39.9411 * 1E6),
				(int) (116.3714 * 1E6));
		GeoPoint p2 = new GeoPoint((int) (39.9498 * 1E6),
				(int) (116.3785 * 1E6));
		GeoPoint p3 = new GeoPoint((int) (39.9436 * 1E6),
				(int) (116.4029 * 1E6));
		GeoPoint p4 = new GeoPoint((int) (39.9329 * 1E6),
				(int) (116.4035 * 1E6));
		GeoPoint p5 = new GeoPoint((int) (39.9218 * 1E6),
				(int) (116.4115 * 1E6));
		GeoPoint p6 = new GeoPoint((int) (39.9144 * 1E6),
				(int) (116.4230 * 1E6));
		GeoPoint p7 = new GeoPoint((int) (39.9126 * 1E6),
				(int) (116.4387 * 1E6));
		// 起點坐标
		GeoPoint start = p1;
		// 終點坐标
		GeoPoint stop = p7;
		// 第一站,站點坐标為p3,經過p1,p2
		GeoPoint[] step1 = new GeoPoint[3];
		step1[0] = p1;
		step1[1] = p2;
		step1[2] = p3;
		// 第二站,站點坐标為p5,經過p4
		GeoPoint[] step2 = new GeoPoint[2];
		step2[0] = p4;
		step2[1] = p5;
		// 第三站,站點坐标為p7,經過p6
		GeoPoint[] step3 = new GeoPoint[2];
		step3[0] = p6;
		step3[1] = p7;
		// 站點資料儲存在一個二維資料中
		GeoPoint[][] routeData = new GeoPoint[3][];
		routeData[0] = step1;
		routeData[1] = step2;
		routeData[2] = step3;
		// 用站點資料建構一個MKRoute
		MKRoute route = new MKRoute();
		route.customizeRoute(start, stop, routeData);
		// 将包含站點資訊的MKRoute添加到RouteOverlay中
		RouteOverlay routeOverlay = new RouteOverlay(
				CustomRouteOverlayActivity.this, mMapView);
		routeOverlay.setData(route);
		// 向地圖添加構造好的RouteOverlay
		mMapView.getOverlays().add(routeOverlay);
		// 執行重新整理使生效
		mMapView.refresh();

	}

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

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

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

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

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

自設路線之布局檔案:

<?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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自設路線功能示範開發者如何自已設定一條路線資料,包括如何設定起點、終點和中間的關鍵節點。以下展示如何在北京地圖上繪制一條形如北鬥七星的路線" />

    <com.baidu.mapapi.map.MapView
        android:id="@+id/bmapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true" />

</LinearLayout>
           

配置檔案和Application類同之前。

附上圖檔效果:

百度地圖之路線規劃
百度地圖之路線規劃