百度地图之路线规划

在前面的一篇文章中介绍过查询公交路线,不过那是根据公交路线的编号进行查询,而且也只是按公交搜索,在本文中,将介绍根据起终点按驾车、公交、步行三种方式进行搜索,功能更为强大,而且同样可以浏览节点,不过百度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类同之前。


附上图片效果:


 

posted on 2013-09-13 21:04  新一  阅读(976)  评论(0编辑  收藏  举报

导航