Android百度地图API实现定位与目的地导航

来源:互联网 发布:巴朗托福 知乎 编辑:程序博客网 时间:2024/06/11 00:00

前几天百度举办了百度世界大会,可惜没去参加,之前参加了百度的开发者大会,在会上也了解了百度的产品,百度现在朝着平台化的方向在发展,感觉很不错,也试用了百度的产品,现在就用着百度的网盘,今天看了下百度地图的开放API,然后做了个Demo,这里分享出来。如果应用主要针对国内市场的话,用百度地图还是一个比较不错的选择。另外,百度还有一个PCS(Personal cloud storage)个人云存储,我比较感兴趣,之后也会继续研究,然后做个Demo分享给大家。今天就先看看这个利用百度地图定位并实现目的地导航的Demo。首先看实现效果:


进入后首先会得到当前位置,在地图上显示出来,在输入框中输入目的地后,就会在地图上出现最佳线路,我这里设置的是距离最小的驾车线路,另外还有公交线路、步行线路,在代码中都有详细注释。另外,在控制台还输出了线路上每一个节点的信息以及起始位置和目的地的距离,信息显示的是在当前节点的导航信息。如下图:



接下来就看如何实现了,首先,注册百度开发者账号,并进入百度地图API查看相关资料百度地图API,然后就是为需要加入地图的应用注册APP KEY,注册完后,下载百度地图jar文件,新建工程,并导入即可,下面看实现具体代码,在代码中有详细注释:

[cpp] view plaincopyprint?
  1. public class NavigationDemoActivity extends MapActivity {
  2. private String mMapKey = "注册自己的key";
  3. private EditText destinationEditText = null;
  4. private Button startNaviButton = null;
  5. private MapView mapView = null;
  6. private BMapManager mMapManager = null;
  7. private MyLocationOverlay myLocationOverlay = null;
  8. //onResume时注册此listener,onPause时需要Remove,注意此listener不是Android自带的,是百度API中的
  9. private LocationListener locationListener;
  10. private MKSearch searchModel;
  11. GeoPoint pt;
  12. @Override
  13. public void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. requestWindowFeature(Window.FEATURE_NO_TITLE);
  16. setContentView(R.layout.main);
  17. destinationEditText = (EditText) this.findViewById(R.id.et_destination);
  18. startNaviButton = (Button) this.findViewById(R.id.btn_navi);
  19. mMapManager = new BMapManager(getApplication());
  20. mMapManager.init(mMapKey, new MyGeneralListener());
  21. super.initMapActivity(mMapManager);
  22. mapView = (MapView) this.findViewById(R.id.bmapsView);
  23. //设置启用内置的缩放控件
  24. mapView.setBuiltInZoomControls(true);
  25. //设置在缩放动画过程中也显示overlay,默认为不绘制
  26. // mapView.setDrawOverlayWhenZooming(true);
  27. //获取当前位置层
  28. myLocationOverlay = new MyLocationOverlay(this, mapView);
  29. //将当前位置的层添加到地图底层中
  30. mapView.getOverlays().add(myLocationOverlay);
  31. // 注册定位事件
  32. locationListener = new LocationListener(){
  33. @Override
  34. public void onLocationChanged(Location location) {
  35. if (location != null){
  36. //生成GEO类型坐标并在地图上定位到该坐标标示的地点
  37. pt = new GeoPoint((int)(location.getLatitude()*1e6),
  38. (int)(location.getLongitude()*1e6));
  39. // System.out.println("---"+location.getLatitude() +":"+location.getLongitude());
  40. mapView.getController().animateTo(pt);
  41. }
  42. }
  43. };
  44. //初始化搜索模块
  45. searchModel = new MKSearch();
  46. //设置路线策略为最短距离
  47. searchModel.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST);
  48. searchModel.init(mMapManager, new MKSearchListener() {
  49. //获取驾车路线回调方法
  50. @Override
  51. public void onGetDrivingRouteResult(MKDrivingRouteResult res,int error) {
  52. // 错误号可参考MKEvent中的定义
  53. if (error != 0 || res == null) {
  54. Toast.makeText(NavigationDemoActivity.this,"抱歉,未找到结果", Toast.LENGTH_SHORT).show();
  55. return;
  56. }
  57. RouteOverlay routeOverlay = new RouteOverlay(NavigationDemoActivity.this, mapView);
  58. // 此处仅展示一个方案作为示例
  59. MKRoute route = res.getPlan(0).getRoute(0);
  60. int distanceM = route.getDistance();
  61. String distanceKm = String.valueOf(distanceM / 1000) +"."+String.valueOf(distanceM % 1000);
  62. System.out.println("距离:"+distanceKm+"公里---节点数量:"+route.getNumSteps());
  63. for (int i = 0; i < route.getNumSteps(); i++) {
  64. MKStep step = route.getStep(i);
  65. System.out.println("节点信息:"+step.getContent());
  66. }
  67. routeOverlay.setData(route);
  68. mapView.getOverlays().clear();
  69. mapView.getOverlays().add(routeOverlay);
  70. mapView.invalidate();
  71. mapView.getController().animateTo(res.getStart().pt);
  72. }
  73. //以下两种方式和上面的驾车方案实现方法一样
  74. @Override
  75. public void onGetWalkingRouteResult(MKWalkingRouteResult res,int error) {
  76. //获取步行路线
  77. }
  78. @Override
  79. public void onGetTransitRouteResult(MKTransitRouteResult arg0,int arg1) {
  80. //获取公交线路
  81. }
  82. @Override
  83. public void onGetBusDetailResult(MKBusLineResult arg0,int arg1) {
  84. }
  85. @Override
  86. public void onGetAddrResult(MKAddrInfo arg0,int arg1) {
  87. }
  88. @Override
  89. public void onGetSuggestionResult(MKSuggestionResult arg0,int arg1) {
  90. }
  91. @Override
  92. public void onGetPoiResult(MKPoiResult arg0,int arg1, int arg2) {
  93. }
  94. });
  95. startNaviButton.setOnClickListener(new OnClickListener() {
  96. @Override
  97. public void onClick(View v) {
  98. String destination = destinationEditText.getText().toString();
  99. //设置起始地(当前位置)
  100. MKPlanNode startNode = new MKPlanNode();
  101. startNode.pt = pt;
  102. //设置目的地
  103. MKPlanNode endNode = new MKPlanNode();
  104. endNode.name = destination;
  105. //展开搜索的城市
  106. String city = getResources().getString(R.string.beijing);
  107. // System.out.println("----"+city+"---"+destination+"---"+pt);
  108. searchModel.drivingSearch(city, startNode, city, endNode);
  109. //步行路线
  110. // searchModel.walkingSearch(city, startNode, city, endNode);
  111. //公交路线
  112. // searchModel.transitSearch(city, startNode, endNode);
  113. }
  114. });
  115. }
  116. @Override
  117. protected void onResume() {
  118. mMapManager.getLocationManager().requestLocationUpdates(locationListener);
  119. myLocationOverlay.enableMyLocation();
  120. myLocationOverlay.enableCompass(); // 打开指南针
  121. mMapManager.start();
  122. super.onResume();
  123. }
  124. @Override
  125. protected void onPause() {
  126. mMapManager.getLocationManager().removeUpdates(locationListener);
  127. myLocationOverlay.disableMyLocation();//显示当前位置
  128. myLocationOverlay.disableCompass(); // 关闭指南针
  129. mMapManager.stop();
  130. super.onPause();
  131. }
  132. @Override
  133. protected boolean isRouteDisplayed() {
  134. // TODO Auto-generated method stub
  135. return false;
  136. }
  137. // 常用事件监听,用来处理通常的网络错误,授权验证错误等
  138. class MyGeneralListener implements MKGeneralListener {
  139. @Override
  140. public void onGetNetworkState(int iError) {
  141. Log.d("MyGeneralListener", "onGetNetworkState error is "+ iError);
  142. Toast.makeText(NavigationDemoActivity.this,"您的网络出错啦!",
  143. Toast.LENGTH_LONG).show();
  144. }
  145. @Override
  146. public void onGetPermissionState(int iError) {
  147. Log.d("MyGeneralListener","onGetPermissionState error is "+ iError);
  148. if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
  149. // 授权Key错误:
  150. Toast.makeText(NavigationDemoActivity.this,
  151. "请在BMapApiDemoApp.java文件输入正确的授权Key!",
  152. Toast.LENGTH_LONG).show();
  153. }
  154. }
  155. }
  156. }


 

然后是布局文件:

[html] view plaincopyprint?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <LinearLayout
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:orientation="horizontal">
  10. <TextView
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:textSize="18sp"
  14. android:text="Destination:"/>
  15. <EditText
  16. android:id="@+id/et_destination"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content"/>
  19. </LinearLayout>
  20. <Button
  21. android:id="@+id/btn_navi"
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. android:text="Start navigate"/>
  25. <com.baidu.mapapi.MapView
  26. android:id="@+id/bmapsView"
  27. android:layout_width="fill_parent"
  28. android:layout_height="fill_parent"
  29. android:clickable="true"/>
  30. </LinearLayout>


AndroidMainifest.xml

[html] view plaincopyprint?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.ericssonlabs"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <uses-sdkandroid:minSdkVersion="8"/>
  7. <uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
  8. <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
  9. <uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>
  10. <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  11. <uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
  12. <uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
  13. <uses-permissionandroid:name="android.permission.READ_PHONE_STATE"></uses-permission>
  14. <supports-screensandroid:largeScreens="true"
  15. android:normalScreens="true"android:smallScreens="true"
  16. android:resizeable="true"android:anyDensity="true"/>
  17. <uses-sdkandroid:minSdkVersion="3"></uses-sdk>
  18. <application
  19. android:icon="@drawable/ic_launcher"
  20. android:label="@string/app_name">
  21. <activity
  22. android:name=".NavigationDemoActivity"
  23. android:label="@string/app_name">
  24. <intent-filter>
  25. <actionandroid:name="android.intent.action.MAIN"/>
  26. <categoryandroid:name="android.intent.category.LAUNCHER"/>
  27. </intent-filter>
  28. </activity>
  29. </application>
  30. </manifest>

 

原创粉丝点击