第一次写博客,心里有点小忐忑。不过在Android菜鸟的进阶之路发现写博客也是一种进步。
(转载请注明本文出自DLx2ChEnGYt的博客http://blog.csdn.net/DLx2ChEnGYt/article/details/46377627)尊重他人的辛勤劳动成果,谢谢!
在公司老大的要求下,让我在项目里加上百度地图线路规划的需求,之前是一点不懂,然后看了很久的百度官方的sdk,最后根据百度官方sdk写了自己的一个小DEMO,下面给大家分享下,有需要的同志可以参考。
百度key的申请和配置就不多说了,不了解的通知们可以进百度官方看看:http://developer.baidu.com/map/index.php?title=androidsdk
其实很多同志都写过百度地图的线路规划,不过在官方demo里终点如果设置的非常精确,比如某个电影院的地址,都是找不到结果,所以我参考了下百度地图中的 地理编码,地理编码可以非常精确到找到各种位置,所以就把线路规划和地理编码结合着写,关键在于这一步:
这一步是把经纬度的LatLng转换线路规划中的PlanNode类型,有了这样的了解,其他的就完全可以直接去写了:
PlanNode st = PlanNode.withLocation(new LatLng(39.931867, 116.395645));
PlanNode ed = PlanNode.withLocation(new LatLng(39.915267, 116.40355));
接来下就可开始写了:
package com.example.mapdemo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.TransitRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
/**
* @author xiexucheng
* @author 百度地图线路导航 --> 线路规划 + 地理编码
* 详情请参考百度地图官方SDK
*/
public class MainActivity extends Activity implements OnGetGeoCoderResultListener,
BaiduMap.OnMapClickListener,OnGetRoutePlanResultListener{
private EditText start,end; // 起点 , 终点
private Button drive,transit,walk,shang,xia; //驾车,公交,步行,上节点,下节点
private String City = "北京市";
private TextView tv2,qidian,zhongdian,listnodetitle; //当前位置,起点,终点,节点信息
private Button chakan,btn_over; //查看详情,关闭详情
private LinearLayout linear;
private ListView listView;
GeoCoder mSearch = null; // 地理编码搜索模块,也可去掉地图模块独立使用
RoutePlanSearch Search = null; // 线路规划搜索模块
BaiduMap mBaiduMap = null;
MapView mMapView = null;
private double cityLng; //当前城市 - 维度
private double positionLng;//当前位置 - 经度
private String mMapKey = "Avll9uuG3lX5BktLet5Ec28G"; //百度key
int nodeIndex = -1;//节点索引,供浏览节点时使用
RouteLine route = null;
OverlayManager routeOverlay = null;
boolean useDefaultIcon = false;
private TextView popupText = null;//泡泡view
//获取节结果信息
LatLng nodeLocation = null; //节点位置
String nodeTitle = null; //节点信息
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.baidumapsView);
mBaiduMap = mMapView.getMap();
start = (EditText) findViewById(R.id.start);
end = (EditText) findViewById(R.id.end);
tv2 = (TextView) findViewById(R.id.tv2);
linear = (LinearLayout) findViewById(R.id.linear);
chakan = (Button) findViewById(R.id.chakan);
btn_over = (Button) findViewById(R.id.btn_over);
qidian = (TextView) findViewById(R.id.qidian);
zhongdian = (TextView) findViewById(R.id.zhongdian);
listView = (ListView) findViewById(R.id.listview);
// listnodetitle = (TextView) findViewById(R.id.listnodetitle);
// 初始化搜索模块,注册事件监听 /地理编码
mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(this);
// 初始化搜索模块,注册事件监听 /线路规划
Search = RoutePlanSearch.newInstance();
Search.setOnGetRoutePlanResultListener(this);
hidden();
}
public void searchButtonProcess(View v) {
route = null;
mBaiduMap.clear();
//起点
PlanNode stNode = PlanNode.withCityNameAndPlaceName(City, start.getText().toString());
//终点 - 把地理编码里的LatLng格式转换成PlanNode格式
PlanNode endNode = PlanNode.withLocation(new LatLng(cityLng, positionLng));
// 实际使用中请对起点终点城市进行正确的设定
if (v.getId() == R.id.drive) {
// 地理编码(把地址转换成经纬度)
mSearch.geocode(new GeoCodeOption().city(City).address(end.getText().toString()));
//线路规划
Search.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(endNode));
}else if (v.getId() == R.id.transit) {
//地理编码(把地址转换成经纬度)
mSearch.geocode(new GeoCodeOption().city(City).address(end.getText().toString()));
//线路规划
Search.transitSearch(new TransitRoutePlanOption().from(stNode).city(City).to(endNode));
}else if (v.getId() == R.id.walk) {
//地理编码(把地址转换成经纬度)
mSearch.geocode(new GeoCodeOption().city(City).address(end.getText().toString()));
//线路规划
Search.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(endNode));
}
tv2.setText(start.getText().toString());
}
//****************** 地理编码 ***************************
@Override
public void onGetGeoCodeResult(GeoCodeResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MainActivity.this, "抱歉,未能找到结果", Toast.LENGTH_LONG).show();
return;
}
mBaiduMap.clear();
//地理编码定位 -演示时可以取消注释 (注:因为在整个demo里 点击三种路线时 它会先定位到目的地 然后才会显示出路线 用户体验缺失 所以注释掉定位.直接显示路线)
// mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
// mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result.getLocation()));
//得到经纬度
String strInfo = String.format("纬度:%f 经度:%f", result.getLocation().latitude, result.getLocation().longitude);
// Toast.makeText(MainActivity.this, strInfo, Toast.LENGTH_SHORT).show();
Log.i("XXX", "纬度:===》"+result.getLocation().latitude);
Log.i("XXX", "经度:===》"+result.getLocation().longitude);
cityLng = result.getLocation().latitude;
positionLng = result.getLocation().longitude;
}
/**
* 这个没用上 如果需要的话可以在建两个Editext 用于输经纬度 可以转换成 文字地址
* 详情请看百度官方SDK
*/
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MainActivity.this, "抱歉,未能找到结果", Toast.LENGTH_LONG).show();
return;
}
mBaiduMap.clear();
mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result.getLocation()));
Toast.makeText(MainActivity.this, result.getAddress(),Toast.LENGTH_LONG).show();
}
//**************** 线路规划 ************************
/**
* 节点浏览示例
* @param xiexucheng
*/
public void nodeClick(View v) {
if (route == null ||
route.getAllStep() == null) {
return;
}
if (nodeIndex == -1 && v.getId() == R.id.shang) {
return;
}
//设置节点索引
if (v.getId() == R.id.xia) {
if (nodeIndex < route.getAllStep().size() - 1) {
nodeIndex++;
} else {
return;
}
} else if (v.getId() == R.id.shang) {
if (nodeIndex > 0) {
nodeIndex--;
} else {
return;
}
}
Object step = route.getAllStep().get(nodeIndex);
//如果节点索引线路改变 则改变节点的位置和名称
if (step instanceof DrivingRouteLine.DrivingStep) {
nodeLocation = ((DrivingRouteLine.DrivingStep) step).getEntrace().getLocation();
nodeTitle = ((DrivingRouteLine.DrivingStep) step).getInstructions();
} else if (step instanceof WalkingRouteLine.WalkingStep) {
nodeLocation = ((WalkingRouteLine.WalkingStep) step).getEntrace().getLocation();
nodeTitle = ((WalkingRouteLine.WalkingStep) step).getInstructions();
} else if (step instanceof TransitRouteLine.TransitStep) {
nodeLocation = ((TransitRouteLine.TransitStep) step).getEntrace().getLocation();
nodeTitle = ((TransitRouteLine.TransitStep) step).getInstructions();
}
if (nodeLocation == null || nodeTitle == null) {
return;
}
//移动节点至中心
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(nodeLocation));
// show popup
popupText = new TextView(MainActivity.this);
popupText.setBackgroundResource(R.drawable.map_kuang_press);
popupText.setTextColor(0xFF000000);
popupText.setText(nodeTitle);
mBaiduMap.showInfoWindow(new InfoWindow(popupText, nodeLocation, 0));
//打印单独节点信息
Log.i("XXX", "nodeTitle==》》" + nodeTitle);
}
/**
* 切换路线图标,刷新地图使其生效
* 注意: 起终点图标使用中心对齐.
*/
public void changeRouteIcon(View v) {
if (routeOverlay == null) {
return;
}
useDefaultIcon = !useDefaultIcon;
routeOverlay.removeFromMap();
routeOverlay.addToMap();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override //驾车
public void onGetDrivingRouteResult(DrivingRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MainActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
nodeIndex = -1;
route = result.getRouteLines().get(0);
DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
routeOverlay = overlay;
mBaiduMap.setOnMarkerClickListener(overlay);
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
}
//获取线路规划的第一条方案的线路距离
// int str = result. getRouteLines().get(0).getDistance();
}
@Override //公交
public void onGetTransitRouteResult(TransitRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MainActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
nodeIndex = -1;
route = result.getRouteLines().get(0);
TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaiduMap);
mBaiduMap.setOnMarkerClickListener(overlay);
routeOverlay = overlay;
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
}
}
@Override //步行
public void onGetWalkingRouteResult(WalkingRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MainActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
nodeIndex = -1;
route = result.getRouteLines().get(0);
WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaiduMap);
mBaiduMap.setOnMarkerClickListener(overlay);
routeOverlay = overlay;
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
}
}
//定制驾车路线 RouteOverly
private class MyDrivingRouteOverlay extends DrivingRouteOverlay{
public MyDrivingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
@Override
public BitmapDescriptor getStartMarker() {
if (useDefaultIcon) {
return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
}
return null;
}
@Override
public BitmapDescriptor getTerminalMarker() {
if (useDefaultIcon) {
return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
}
return null;
}
}
//定制步行路线 RouteOverly
private class MyWalkingRouteOverlay extends WalkingRouteOverlay {
public MyWalkingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
@Override
public BitmapDescriptor getStartMarker() {
if (useDefaultIcon) {
return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
}
return null;
}
@Override
public BitmapDescriptor getTerminalMarker() {
if (useDefaultIcon) {
return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
}
return null;
}
}
//定制公交路线 RouteOverly
private class MyTransitRouteOverlay extends TransitRouteOverlay {
public MyTransitRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
@Override
public BitmapDescriptor getStartMarker() {
if (useDefaultIcon) {
return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
}
return null;
}
@Override
public BitmapDescriptor getTerminalMarker() {
if (useDefaultIcon) {
return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
}
return null;
}
}
@Override
public void onMapClick(LatLng point) {
mBaiduMap.hideInfoWindow();
}
@Override
public boolean onMapPoiClick(MapPoi poi) {
return false;
}
@Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
@Override
protected void onResume() {
mMapView.onResume();
super.onResume();
}
@Override
protected void onDestroy() {
mMapView.onDestroy();
//地理编码搜索模块
mSearch.destroy();
//线路规划搜索模块
Search.destroy();
super.onDestroy();
}
//***************** 其他 *************************
/**
* 隐藏比例尺和缩放按钮
*/
public void hidden(){
// 隐藏缩放控件
int childCount = mMapView.getChildCount();
View zoom = null;
for (int i = 0; i < childCount; i++) {
View child = mMapView.getChildAt(i);
if (child instanceof ZoomControls) {
zoom = child;
break;
}
}
zoom.setVisibility(View.GONE);
// 隐藏比例尺控件
int count = mMapView.getChildCount();
View scale = null;
for (int i = 0; i < count; i++) {
View child = mMapView.getChildAt(i);
if (child instanceof ZoomControls) {
scale = child;
break;
}
}
scale.setVisibility(View.GONE);
// 隐藏指南针
UiSettings mUiSettings = mBaiduMap.getUiSettings();
mUiSettings.setCompassEnabled(true);
// 删除百度地图logo
mMapView.removeViewAt(1);
//设置地图的缩放级别 默认显示为20米(支持缩放级别范围为3-18)
MapStatusUpdate statusUpdate = MapStatusUpdateFactory.zoomBy(12);
mBaiduMap.animateMapStatus(statusUpdate);
}
public void Click(View v) {
switch (v.getId()) {
case R.id.chakan:
linear.setVisibility(View.VISIBLE);
qidian.setText(start.getText().toString());
zhongdian.setText(end.getText().toString());
/**
* 遍历所有节点的信息
* 如果想展示效果就在把这个遍历注释掉,把这个事件内的注释都打开
*/
List data = new ArrayList();
for (Object step : route.getAllStep()) {
//如果节点索引线路改变 则改变节点的位置和名称
if (step instanceof DrivingRouteLine.DrivingStep) {
nodeLocation = ((DrivingRouteLine.DrivingStep) step).getEntrace().getLocation();
nodeTitle = ((DrivingRouteLine.DrivingStep) step).getInstructions();
} else if (step instanceof WalkingRouteLine.WalkingStep) {
nodeLocation = ((WalkingRouteLine.WalkingStep) step).getEntrace().getLocation();
nodeTitle = ((WalkingRouteLine.WalkingStep) step).getInstructions();
} else if (step instanceof TransitRouteLine.TransitStep) {
nodeLocation = ((TransitRouteLine.TransitStep) step).getEntrace().getLocation();
nodeTitle = ((TransitRouteLine.TransitStep) step).getInstructions();
}
if (nodeLocation == null || nodeTitle == null) {
return;
}
data.add(nodeTitle);
}
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,data);
listView.setAdapter(adapter);
// listnodetitle.setText(data.toString());
Log.i("XXX", "nodeTitle==》》" + data.toString());
break;
case R.id.btn_over:
linear.setVisibility(View.GONE);
break;
}
}
}
这是XML文件布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<com.baidu.mapapi.map.MapView
android:id="@+id/baidumapsView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="vertical" >
<EditText
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入起点:"
/>
<EditText
android:id="@+id/end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入终点:"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/drive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="searchButtonProcess"
android:layout_weight="1"
android:text="驾车"
/>
<Button
android:id="@+id/transit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="searchButtonProcess"
android:layout_weight="1"
android:text="公交"
/>
<Button
android:id="@+id/walk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="searchButtonProcess"
android:layout_weight="1"
android:text="步行"
/>
<Button
android:id="@+id/shang"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="nodeClick"
android:text="《" />
<Button
android:id="@+id/xia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="nodeClick"
android:text="》" />
LinearLayout>
LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#FFFFFF"
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="18dp"
android:background="@drawable/location" />
<Button
android:id="@+id/chakan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="14dp"
android:text="详情"
android:onClick="Click" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/chakan"
android:layout_alignBottom="@+id/chakan"
android:layout_toRightOf="@+id/tv1"
android:text="当前位置"
android:textSize="16sp" />
RelativeLayout>
<LinearLayout
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:orientation="vertical"
android:visibility="gone"
>
<Button
android:id="@+id/btn_over"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="@drawable/delete"
android:onClick="Click"
/>
<TextView
android:id="@+id/qidian"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="起点"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/down"
/>
<TextView
android:id="@+id/zhongdian"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="终点"
/>
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
LinearLayout>
RelativeLayout>
这就是所有的代码了,如果有哪里不对的地方,欢迎各位来探讨. 我的QQ和邮箱:7907716、[email protected]