Android 百度地图API 定位 导航

简介:

      看看这个利用百度地图定位并实现目的地导航的Demo。

首先看实现效果:

          Android 百度地图API 定位 导航 代码                         Android 百度地图API 定位 导航 代码

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

        Android 百度地图API 定位 导航 代码

 

接下来就看怎样实现了,首先。注冊百度开发人员账号,并进入百度地图API查看相关资料百度地图API,然后就是为须要增加地图的应用注冊APP KEY,注冊完后,下载百度地图jar文件。新建project。并导入就可以。以下看实现具体代码,在代码中有具体凝视:

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

"

                         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(NavigationDemoActivity. this ,  
                             "请在BMapApiDemoApp.java文件输入正确的授权Key!

"

                             Toast.LENGTH_LONG).show(); 
                
            
        
}
然后是布局文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<? 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:layout_width = "wrap_content" 
             android:layout_height = "wrap_content" 
             android:textSize = "18sp" 
             android:text = "Destination:" /> 
   
         < EditText 
             android:id = "@+id/et_destination" 
             android:layout_width = "fill_parent" 
             android:layout_height = "wrap_content" /> 
     </ LinearLayout
       
     < Button  
         android:id = "@+id/btn_navi" 
         android:layout_width = "fill_parent" 
            android:layout_height = "wrap_content" 
            android:text = "Start navigate" /> 
   
     < com.baidu.mapapi.MapView 
         android:id = "@+id/bmapsView" 
         android:layout_width = "fill_parent" 
         android:layout_height = "fill_parent" 
         android:clickable = "true" /> 
   
</ LinearLayout >
AndroidMainifest.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<? xml version = "1.0" encoding = "utf-8" ?> 
< manifest xmlns:android = "http://schemas.android.com/apk/res/android" 
     package = "com.ericssonlabs" 
     android:versionCode = "1" 
     android:versionName = "1.0"
   
     < uses-sdk android:minSdkVersion = "8" /> 
   
     < uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" ></ uses-permission
     < uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" ></ uses-permission
     < uses-permission android:name = "android.permission.INTERNET" ></ uses-permission
     < uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" ></ uses-permission
     < uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" ></ uses-permission >   
     < uses-permission android:name = "android.permission.CHANGE_WIFI_STATE" ></ uses-permission >  
     < uses-permission android:name = "android.permission.READ_PHONE_STATE" ></ uses-permission
       
     < supports-screens android:largeScreens = "true" 
         android:normalScreens = "true" android:smallScreens = "true" 
         android:resizeable = "true" android:anyDensity = "true" /> 
     < uses-sdk android:minSdkVersion = "3" ></ uses-sdk
   
     < application 
         android:icon = "@drawable/ic_launcher" 
         android:label = "@string/app_name"
         < activity 
             android:name = ".NavigationDemoActivity" 
             android:label = "@string/app_name"
             < intent-filter
                 < action android:name = "android.intent.action.MAIN" /> 
   
                 < category android:name = "android.intent.category.LAUNCHER" /> 
             </ intent-filter
         </ activity
     </ application
   
</ manifest >

相关文章
|
6月前
|
存储 机器学习/深度学习 API
Android API Level 到底是什么?和安卓什么关系?应用发布如何知道自己的版本?优雅草卓伊凡
Android API Level 到底是什么?和安卓什么关系?应用发布如何知道自己的版本?优雅草卓伊凡
1009 31
Android API Level 到底是什么?和安卓什么关系?应用发布如何知道自己的版本?优雅草卓伊凡
|
编译器 API Android开发
Android经典实战之Kotlin Multiplatform 中,如何处理不同平台的 API 调用
本文介绍Kotlin Multiplatform (KMP) 中使用 `expect` 和 `actual` 关键字处理多平台API调用的方法。通过共通代码集定义预期API,各平台提供具体实现,编译器确保正确匹配,支持依赖注入、枚举类处理等,实现跨平台代码重用与原生性能。附带示例展示如何定义跨平台函数与类。
507 0
|
定位技术 Android开发 iOS开发
引入百度地图,安卓出现白屏问题
引入百度地图,安卓出现白屏问题
424 57
|
新能源 API
百科-百度免费API接口教程
该接口用于从百度百科获取指定名词的基础解释。支持POST或GET请求,需提供用户ID、用户KEY及查询内容。返回状态码和解释内容或错误提示。示例:https://cn.apihz.cn/api/zici/baikebaidu.php?id=88888888&key=88888888&words=汽车。建议使用个人ID与KEY以享受更高调用频次。
1559 4
|
API
表情包-百度版免费API接口教程
该接口用于通过指定关键词从百度渠道获取表情包,支持POST或GET请求。需提供用户ID和KEY,可选参数包括关键词、页码及结果数量。返回数据包含状态码、信息提示、结果集等。示例中ID与KEY为公共测试用,建议使用个人ID与KEY以享受更高调用频率。
1517 4
|
API
通用图片搜索-百度源免费API接口教程
该接口用于搜索百度图片,支持通过关键词、页码、结果数量等参数获取图片搜索结果。请求方式为POST或GET,需提供用户ID和KEY,可选参数包括关键词、页码、结果数量及返回源类型。返回结果包含状态码、信息提示、结果集、当前页码、最大页码和结果数量。示例中提供了GET和POST请求方法及返回数据示例。
1823 4
|
JavaScript 前端开发 定位技术
百度地图JavaScript API v2.0创建地图
百度地图JavaScript API v2.0创建地图
224 0
|
3月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。