`

百度地图的手动定位和自动定位[转]

 
阅读更多

 

http://aokunsang.iteye.com/blog/1119075

 

最近由于项目需要,研究了下百度地图定位,他们提供的实例基本都是用监听器实现自动定位的。我想实现一种效果:当用户进入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.     
  8.   <TextView   
  9.     android:id="@+id/myLocation_id"   
  10.     android:layout_width="fill_parent"   
  11.     android:layout_height="wrap_content"  
  12.     android:textSize="15dp"  
  13.     android:gravity="center_horizontal"  
  14.     android:textColor="@drawable/black"  
  15.     android:background="@drawable/gary"  
  16.     />  
  17.       
  18.   <com.baidu.mapapi.MapView android:id="@+id/bmapsView"  
  19.     android:layout_width="fill_parent" android:layout_height="fill_parent"   
  20.     android:clickable="true"  android:layout_weight="1"     
  21.    />  
  22.     
  23.   <Button   
  24.       android:layout_width="wrap_content"   
  25.       android:layout_height="wrap_content"   
  26.       android:id="@+id/location_button_id"   
  27.       android:text="@string/location_button_text"  
  28.    />  
  29.       
  30. </LinearLayout>  

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

 

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

 

Java代码  收藏代码
  1. public BMapManager mapManager = null;  
  2. static MapApplication app;  
  3. public String mStrKey = "你申请的key值";  
  4.   
  5. @Override  
  6. public void onCreate() {  
  7.     mapManager = new BMapManager(this);  
  8.     mapManager.init(mStrKey, new MyGeneralListener());  
  9. }  
  10. @Override  
  11. //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗  
  12. public void onTerminate() {  
  13.     // TODO Auto-generated method stub  
  14.     if(mapManager != null)  
  15.     {  
  16.         mapManager.destroy();  
  17.         mapManager = null;  
  18.     }  
  19.     super.onTerminate();  
  20. }  
  21.   
  22.  static class MyGeneralListener implements MKGeneralListener{  
  23.   
  24.     @Override  
  25.     public void onGetNetworkState(int arg0) {  
  26.         Toast.makeText(MapApplication.app.getApplicationContext(), "您的网络出错啦!",  
  27.                 Toast.LENGTH_LONG).show();  
  28.     }  
  29.     @Override  
  30.     public void onGetPermissionState(int iError) {  
  31.         if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {  
  32.             // 授权Key错误:  
  33.             Toast.makeText(MapApplication.app.getApplicationContext(),"您的授权Key不正确!",  
  34.                     Toast.LENGTH_LONG).show();  
  35.         }  
  36.     }  
  37. }  
  38. 5、接下来就是按照百度api写定位代码了,使用handler机制去添加定位图层,需要说明的都在注释上了。  
  39.   
  40.        private BMapManager mBMapMan = null;  
  41. private MapView mMapView = null;  
  42. private MapController bMapController;  
  43. private MKLocationManager mkLocationManager;  
  44. private MKSearch mkSearch;  
  45.   
  46. private TextView address_view;   //定位到的位置信息  
  47.   
  48. private ProgressDialog dialog;  
  49. private List<HotelInfo> hotelList;  
  50.   
  51. private int distance = 1000;  //查询的范围(单位:m)  
  52.   
  53.    Handler handler = new Handler(){  
  54.     @Override  
  55.     public void handleMessage(Message msg) {  
  56.           
  57.         double lat = msg.getData().getDouble("lat");  
  58.         double lon = msg.getData().getDouble("lon");  
  59.         if(lat!=0&&lon!=0){  
  60.             GeoPoint point = new GeoPoint(  
  61.                     (int) (lat * 1E6),  
  62.                     (int) (lon * 1E6));  
  63.             bMapController.animateTo(point);  //设置地图中心点  
  64.             bMapController.setZoom(15);  
  65.               
  66.             mkSearch.reverseGeocode(point);   //解析地址(异步方法)  
  67.               
  68.             MyLocationOverlay myLoc = new MyLocationOverlayFromMap(ShowMapAct.this,mMapView);  
  69.             myLoc.enableMyLocation();   // 启用定位  
  70.             myLoc.enableCompass();      // 启用指南针  
  71.             mMapView.getOverlays().add(myLoc);  
  72.         }else{  
  73.             Toast.makeText(ShowMapAct.this"没有加载到您的位置", Toast.LENGTH_LONG).show();  
  74.         }  
  75.           
  76.         if(hotelList!=null){  
  77.             Drawable marker = getResources().getDrawable(R.drawable.iconmarka);  //设置marker  
  78.             marker.setBounds(00, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());   //为maker定义位置和边界  
  79.             mMapView.getOverlays().add(new OverItemList(marker,hotelList,ShowMapAct.this,bMapController));  
  80.         }else if(hotelList==null&&lat!=0&&lon!=0){  
  81.             Toast.makeText(ShowMapAct.this"网络异常,没有获取到酒店信息。", Toast.LENGTH_LONG).show();  
  82.         }  
  83.         if(dialog!=null)  dialog.dismiss();  
  84.     }  
  85.   };  
  86.   
  87. @Override  
  88. protected void onCreate(Bundle savedInstanceState) {  
  89.       
  90.     distance = getIntent().getExtras().getInt("distance");   //获取查询范围  
  91.       
  92.     super.onCreate(savedInstanceState);  
  93.     setContentView(R.layout.location);  
  94.       
  95.     mMapView = (MapView)findViewById(R.id.bmapsView);   //初始化一个mapView  存放Map  
  96.     init();  //初始化地图管理器  
  97.     super.initMapActivity(mBMapMan);  
  98.       
  99.       
  100.     address_view = (TextView)findViewById(R.id.myLocation_id);  
  101.     SpannableStringBuilder style = new SpannableStringBuilder(String.format(getResources().getString(R.string.location_text),"位置不详"));  
  102.     style.setSpan(new ForegroundColorSpan(Color.RED), 5, style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  103.     address_view.setText(style);  
  104.       
  105.     Button location_button = (Button)findViewById(R.id.location_button_id);  
  106.     location_button.setOnClickListener(new View.OnClickListener(){  
  107.         @Override  
  108.         public void onClick(View v) {  
  109.              dialog = ProgressDialog.show(ShowMapAct.this"""数据加载中,请稍后.....");  
  110.              new Thread(new MyThread()).start();  
  111.         }  
  112.     });  
  113.       
  114.     mkSearch = new MKSearch();   //初始化一个MKSearch,根据location解析详细地址  
  115.     mkSearch.init(mBMapMan, this);  
  116.        mMapView.setBuiltInZoomControls(true);   //启用内置的缩放控件  
  117.        bMapController = mMapView.getController();  
  118.        GeoPoint defaultPoint = new GeoPoint((int) (39.920934 * 1E6),(int) (116.412817 * 1E6));  //用给定的经纬度构造一个GeoPoint,单位是微度 (度 * 1E6)  
  119.        bMapController.setCenter(defaultPoint);  //设置地图中心点  
  120.        bMapController.setZoom(12);  //设置地图zoom级别  
  121.          
  122.        mkLocationManager = mBMapMan.getLocationManager();  
  123. }  
  124. /** 
  125.  * 初始化地图管理器BMapManager 
  126.  */  
  127. public void init(){  
  128.     MapApplication app = (MapApplication)getApplication();  
  129.        if (app.mapManager == null) {  
  130.         app.mapManager = new BMapManager(getApplication());  
  131.         app.mapManager.init(app.mStrKey, new MapApplication.MyGeneralListener());  
  132.        }  
  133.        mBMapMan = app.mapManager;  
  134. }  
  135.   
  136. @Override  
  137. protected void onDestroy() {  
  138.     MapApplication app = (MapApplication)getApplication();  
  139.     if (mBMapMan != null) {  
  140.         mBMapMan.destroy();  
  141.         app.mapManager.destroy();  
  142.         app.mapManager = null;  
  143.         mBMapMan = null;  
  144.     }  
  145.     super.onDestroy();  
  146. }  
  147.   
  148.    
  149.    @Override    
  150.    protected void onPause() {    
  151.        if (mBMapMan != null) {    
  152.            // 终止百度地图API    
  153.         mBMapMan.stop();    
  154.        }    
  155.        super.onPause();    
  156.    }  
  157.    
  158.    @Override    
  159.    protected void onResume() {  
  160.        if (mBMapMan != null) {    
  161.            // 开启百度地图API    
  162.         mBMapMan.start();    
  163.        }    
  164.        super.onResume();    
  165.    }  
  166.   
  167. @Override  
  168. protected boolean isRouteDisplayed() {  
  169.     return false;  
  170. }  
  171.   
  172. @Override  
  173. public void onGetAddrResult(MKAddrInfo result, int iError) {  
  174.     if(result==nullreturn;  
  175.     SpannableStringBuilder style = new SpannableStringBuilder(String.format(getResources().getString(R.string.location_text),result.strAddr));  
  176.     style.setSpan(new ForegroundColorSpan(Color.RED), 5, style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  177.     address_view.setText(style);  
  178.     if(dialog!=null) dialog.dismiss();  
  179. }  
  180.   
  181. @Override  
  182. public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {}  
  183. @Override  
  184. public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {}  
  185. @Override  
  186. public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {}  
  187. @Override  
  188. public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {}  
  189.   
  190. /** 
  191.  * 重新定位,加载数据 
  192.  * @author Administrator 
  193.  * 
  194.  */  
  195. class MyThread implements Runnable{  
  196.     @Override  
  197.     public void run() {  
  198.         /** 
  199.           * 最重要的就是这个玩意 
  200.           * 由于LocationListener获取第一个位置修正的时间会很长,为了避免用户等待, 
  201.           * 在LocationListener获取第一个更精确的位置之前,应当使用getLocationInfo() 获取一个缓存的位置 
  202.           */  
  203.         Location location = mkLocationManager.getLocationInfo();  
  204.         double lat = 0d,lon = 0d;  
  205.         if(location!=null){   //定位到位置  
  206.             String coordinate = location.getLatitude()+","+location.getLongitude();  
  207.             HotelRemoteData hotelData = new HotelRemoteData();  
  208.             /** 
  209.              * 远程获取酒店列表数据 
  210.              */  
  211.             hotelList = hotelData.getHotelToMap(coordinate,distance);  
  212.             lat = location.getLatitude();  
  213.             lon = location.getLongitude();  
  214.         }  
  215.           
  216.         Message msg = new Message();  
  217.         Bundle data = new Bundle();  
  218.         data.putDouble("lat", lat);  
  219.         data.putDouble("lon", lon);  
  220.         msg.setData(data);  
  221.         handler.sendMessage(msg);  
  222.     }  
  223. }  
 

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

 

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics