`
king_tt
  • 浏览: 2111152 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Android 百度地图定位(手动+自动)

 
阅读更多
最近由于项目需要,研究了下百度地图定位,他们提供的实例基本都是用监听器实现自动定位的。我想实现一种效果:当用户进入UI时,不定位,用户需要定位的时候,自己手动点击按钮,再去定位当前位置。 经过2天研究和咨询,找到了解决方案,在此备忘一下。

注意:定位使用真机才能够真正定位;模拟器的话,在DDMS中的Emulator Control中,选择Manual,下面单选按钮选择Decimal,然后填写经纬度,send后,再点击定位我的位置按钮,就能定位了(这应该算是固定定位,哈哈。。。)、

1、第一步当然是获取一个针对自己项目的key值。http://dev.baidu.com/wiki/static/imap/key/

2、使用百度API是有前提的,摘自百度:首先将API包括的两个文件baidumapapi.jar和libBMapApiEngine.so拷贝到工程根目录及libs\armeabi目录下,并在工程属性->Java Build Path->Libraries中选择“Add JARs”,选定baidumapapi.jar,确定后返回,这样您就可以在您的程序中使用API了。(这两个文件见附件)。

3、按照自己的需求写一个layout,我的如下:

<?xml version="1.0" encoding="utf-8"?>

Xml代码 收藏代码
  1. <LinearLayout
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:id="@+id/myLocation_id"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:textSize="15dp"
  12. android:gravity="center_horizontal"
  13. android:textColor="@drawable/black"
  14. android:background="@drawable/gary"
  15. />
  16. <com.baidu.mapapi.MapViewandroid:id="@+id/bmapsView"
  17. android:layout_width="fill_parent"android:layout_height="fill_parent"
  18. android:clickable="true"android:layout_weight="1"
  19. />
  20. <Button
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:id="@+id/location_button_id"
  24. android:text="@string/location_button_text"
  25. />
  26. </LinearLayout>

需要特别注意的是:<com.baidu.mapapi.MapView /> 这玩意。

4、写一个MapApplication实现application,提供全局的BMapManager,以及其初始化。

Java代码 收藏代码
  1. publicBMapManagermapManager=null;
  2. staticMapApplicationapp;
  3. publicStringmStrKey="你申请的key值";
  4. @Override
  5. publicvoidonCreate(){
  6. mapManager=newBMapManager(this);
  7. mapManager.init(mStrKey,newMyGeneralListener());
  8. }
  9. @Override
  10. //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗
  11. publicvoidonTerminate(){
  12. //TODOAuto-generatedmethodstub
  13. if(mapManager!=null)
  14. {
  15. mapManager.destroy();
  16. mapManager=null;
  17. }
  18. super.onTerminate();
  19. }
  20. staticclassMyGeneralListenerimplementsMKGeneralListener{
  21. @Override
  22. publicvoidonGetNetworkState(intarg0){
  23. Toast.makeText(MapApplication.app.getApplicationContext(),"您的网络出错啦!",
  24. Toast.LENGTH_LONG).show();
  25. }
  26. @Override
  27. publicvoidonGetPermissionState(intiError){
  28. if(iError==MKEvent.ERROR_PERMISSION_DENIED){
  29. //授权Key错误:
  30. Toast.makeText(MapApplication.app.getApplicationContext(),"您的授权Key不正确!",
  31. Toast.LENGTH_LONG).show();
  32. }
  33. }
  34. }
  35. 5、接下来就是按照百度api写定位代码了,使用handler机制去添加定位图层,需要说明的都在注释上了。
  36. privateBMapManagermBMapMan=null;
  37. privateMapViewmMapView=null;
  38. privateMapControllerbMapController;
  39. privateMKLocationManagermkLocationManager;
  40. privateMKSearchmkSearch;
  41. privateTextViewaddress_view;//定位到的位置信息
  42. privateProgressDialogdialog;
  43. privateList<HotelInfo>hotelList;
  44. privateintdistance=1000;//查询的范围(单位:m)
  45. Handlerhandler=newHandler(){
  46. @Override
  47. publicvoidhandleMessage(Messagemsg){
  48. doublelat=msg.getData().getDouble("lat");
  49. doublelon=msg.getData().getDouble("lon");
  50. if(lat!=0&&lon!=0){
  51. GeoPointpoint=newGeoPoint(
  52. (int)(lat*1E6),
  53. (int)(lon*1E6));
  54. bMapController.animateTo(point);//设置地图中心点
  55. bMapController.setZoom(15);
  56. mkSearch.reverseGeocode(point);//解析地址(异步方法)
  57. MyLocationOverlaymyLoc=newMyLocationOverlayFromMap(ShowMapAct.this,mMapView);
  58. myLoc.enableMyLocation();//启用定位
  59. myLoc.enableCompass();//启用指南针
  60. mMapView.getOverlays().add(myLoc);
  61. }else{
  62. Toast.makeText(ShowMapAct.this,"没有加载到您的位置",Toast.LENGTH_LONG).show();
  63. }
  64. if(hotelList!=null){
  65. Drawablemarker=getResources().getDrawable(R.drawable.iconmarka);//设置marker
  66. marker.setBounds(0,0,marker.getIntrinsicWidth(),marker.getIntrinsicHeight());//为maker定义位置和边界
  67. mMapView.getOverlays().add(newOverItemList(marker,hotelList,ShowMapAct.this,bMapController));
  68. }elseif(hotelList==null&&lat!=0&&lon!=0){
  69. Toast.makeText(ShowMapAct.this,"网络异常,没有获取到酒店信息。",Toast.LENGTH_LONG).show();
  70. }
  71. if(dialog!=null)dialog.dismiss();
  72. }
  73. };
  74. @Override
  75. protectedvoidonCreate(BundlesavedInstanceState){
  76. distance=getIntent().getExtras().getInt("distance");//获取查询范围
  77. super.onCreate(savedInstanceState);
  78. setContentView(R.layout.location);
  79. mMapView=(MapView)findViewById(R.id.bmapsView);//初始化一个mapView存放Map
  80. init();//初始化地图管理器
  81. super.initMapActivity(mBMapMan);
  82. address_view=(TextView)findViewById(R.id.myLocation_id);
  83. SpannableStringBuilderstyle=newSpannableStringBuilder(String.format(getResources().getString(R.string.location_text),"位置不详"));
  84. style.setSpan(newForegroundColorSpan(Color.RED),5,style.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  85. address_view.setText(style);
  86. Buttonlocation_button=(Button)findViewById(R.id.location_button_id);
  87. location_button.setOnClickListener(newView.OnClickListener(){
  88. @Override
  89. publicvoidonClick(Viewv){
  90. dialog=ProgressDialog.show(ShowMapAct.this,"","数据加载中,请稍后.....");
  91. newThread(newMyThread()).start();
  92. }
  93. });
  94. mkSearch=newMKSearch();//初始化一个MKSearch,根据location解析详细地址
  95. mkSearch.init(mBMapMan,this);
  96. mMapView.setBuiltInZoomControls(true);//启用内置的缩放控件
  97. bMapController=mMapView.getController();
  98. GeoPointdefaultPoint=newGeoPoint((int)(39.920934*1E6),(int)(116.412817*1E6));//用给定的经纬度构造一个GeoPoint,单位是微度(度*1E6)
  99. bMapController.setCenter(defaultPoint);//设置地图中心点
  100. bMapController.setZoom(12);//设置地图zoom级别
  101. mkLocationManager=mBMapMan.getLocationManager();
  102. }
  103. /**
  104. *初始化地图管理器BMapManager
  105. */
  106. publicvoidinit(){
  107. MapApplicationapp=(MapApplication)getApplication();
  108. if(app.mapManager==null){
  109. app.mapManager=newBMapManager(getApplication());
  110. app.mapManager.init(app.mStrKey,newMapApplication.MyGeneralListener());
  111. }
  112. mBMapMan=app.mapManager;
  113. }
  114. @Override
  115. protectedvoidonDestroy(){
  116. MapApplicationapp=(MapApplication)getApplication();
  117. if(mBMapMan!=null){
  118. mBMapMan.destroy();
  119. app.mapManager.destroy();
  120. app.mapManager=null;
  121. mBMapMan=null;
  122. }
  123. super.onDestroy();
  124. }
  125. @Override
  126. protectedvoidonPause(){
  127. if(mBMapMan!=null){
  128. //终止百度地图API
  129. mBMapMan.stop();
  130. }
  131. super.onPause();
  132. }
  133. @Override
  134. protectedvoidonResume(){
  135. if(mBMapMan!=null){
  136. //开启百度地图API
  137. mBMapMan.start();
  138. }
  139. super.onResume();
  140. }
  141. @Override
  142. protectedbooleanisRouteDisplayed(){
  143. returnfalse;
  144. }
  145. @Override
  146. publicvoidonGetAddrResult(MKAddrInforesult,intiError){
  147. if(result==null)return;
  148. SpannableStringBuilderstyle=newSpannableStringBuilder(String.format(getResources().getString(R.string.location_text),result.strAddr));
  149. style.setSpan(newForegroundColorSpan(Color.RED),5,style.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  150. address_view.setText(style);
  151. if(dialog!=null)dialog.dismiss();
  152. }
  153. @Override
  154. publicvoidonGetDrivingRouteResult(MKDrivingRouteResultarg0,intarg1){}
  155. @Override
  156. publicvoidonGetPoiResult(MKPoiResultarg0,intarg1,intarg2){}
  157. @Override
  158. publicvoidonGetTransitRouteResult(MKTransitRouteResultarg0,intarg1){}
  159. @Override
  160. publicvoidonGetWalkingRouteResult(MKWalkingRouteResultarg0,intarg1){}
  161. /**
  162. *重新定位,加载数据
  163. *@authorAdministrator
  164. *
  165. */
  166. classMyThreadimplementsRunnable{
  167. @Override
  168. publicvoidrun(){
  169. /**
  170. *最重要的就是这个玩意
  171. *由于LocationListener获取第一个位置修正的时间会很长,为了避免用户等待,
  172. *在LocationListener获取第一个更精确的位置之前,应当使用getLocationInfo()获取一个缓存的位置
  173. */
  174. Locationlocation=mkLocationManager.getLocationInfo();
  175. doublelat=0d,lon=0d;
  176. if(location!=null){//定位到位置
  177. Stringcoordinate=location.getLatitude()+","+location.getLongitude();
  178. HotelRemoteDatahotelData=newHotelRemoteData();
  179. /**
  180. *远程获取酒店列表数据
  181. */
  182. hotelList=hotelData.getHotelToMap(coordinate,distance);
  183. lat=location.getLatitude();
  184. lon=location.getLongitude();
  185. }
  186. Messagemsg=newMessage();
  187. Bundledata=newBundle();
  188. data.putDouble("lat",lat);
  189. data.putDouble("lon",lon);
  190. msg.setData(data);
  191. handler.sendMessage(msg);
  192. }
  193. }

6、还有一种就是百度示例相当推荐的,也是加载定位位置速度比较快的,那就是通过定位监听器来定位信息。没啥难的,照着百度的示例写,都能搞定。

Java代码 收藏代码
  1. LocationListenerlistener=newLocationListener(){
  2. @Override
  3. /**位置变化,百度地图即会调用该方法去获取位置信息。
  4. *(我测试发现就算手机不动,它也会偶尔重新去加载位置;只要你通过重力感应,他就一定会重新加载)
  5. */
  6. publicvoidonLocationChanged(Locationlocation){
  7. GeoPointgp=newGeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));//通过地图上的经纬度转换为地图上的坐标点
  8. bMapController.animateTo(gp);//动画般的移动到定位的位置
  9. }
  10. };


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics