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拷贝到工程根目录及libsarmeabi目录下,并在工程属性->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. @Override 

  5. public void onCreate() { 

  6.     mapManager = new BMapManager(this); 

  7.     mapManager.init(mStrKey, new MyGeneralListener()); 

  8. @Override 

  9. //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗 

  10. public void onTerminate() { 

  11.     // TODO Auto-generated method stub 

  12.     if(mapManager != null) 

  13.     { 

  14.         mapManager.destroy(); 

  15.         mapManager = null; 

  16.     } 

  17.     super.onTerminate(); 

  18. static class MyGeneralListener implements MKGeneralListener{ 

  19.     @Override 

  20.     public void onGetNetworkState(int arg0) { 

  21.         Toast.makeText(MapApplication.app.getApplicationContext(), "您的网络出错啦!", 

  22.                 Toast.LENGTH_LONG).show(); 

  23.     } 

  24.     @Override 

  25.     public void onGetPermissionState(int iError) { 

  26.         if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) { 

  27.             // 授权Key错误: 

  28.             Toast.makeText(MapApplication.app.getApplicationContext(),"您的授权Key不正确!", 

  29.                     Toast.LENGTH_LONG).show(); 

  30.         } 

  31.     } 

  32. 5、接下来就是按照百度api写定位代码了,使用handler机制去添加定位图层,需要说明的都在注释上了。 

  33.        private BMapManager mBMapMan = null; 

  34. private MapView mMapView = null; 

  35. private MapController bMapController; 

  36. private MKLocationManager mkLocationManager; 

  37. private MKSearch mkSearch; 

  38. private TextView address_view;   //定位到的位置信息 

  39. private ProgressDialog dialog; 

  40. private List<HotelInfo> hotelList; 

  41. private int distance = 1000;  //查询的范围(单位:m) 

  42.    Handler handler = new Handler(){ 

  43.     @Override 

  44.     public void handleMessage(Message msg) { 

  45.          

  46.         double lat = msg.getData().getDouble("lat"); 

  47.         double lon = msg.getData().getDouble("lon"); 

  48.         if(lat!=0&&lon!=0){ 

  49.             GeoPoint point = new GeoPoint( 

  50.                     (int) (lat * 1E6), 

  51.                     (int) (lon * 1E6)); 

  52.             bMapController.animateTo(point);  //设置地图中心点 

  53.             bMapController.setZoom(15); 

  54.              

  55.             mkSearch.reverseGeocode(point);   //解析地址(异步方法) 

  56.              

  57.             MyLocationOverlay myLoc = new MyLocationOverlayFromMap(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.          

  65.         if(hotelList!=null){ 

  66.             Drawable marker = getResources().getDrawable(R.drawable.iconmarka);  //设置marker 

  67.             marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());   //为maker定义位置和边界 

  68.             mMapView.getOverlays().add(new OverItemList(marker,hotelList,ShowMapAct.this,bMapController)); 

  69.         }else if(hotelList==null&&lat!=0&&lon!=0){ 

  70.             Toast.makeText(ShowMapAct.this, "网络异常,没有获取到酒店信息。", Toast.LENGTH_LONG).show(); 

  71.         } 

  72.         if(dialog!=null)  dialog.dismiss(); 

  73.     } 

  74.   }; 

  75. @Override 

  76. protected void onCreate(Bundle savedInstanceState) { 

  77.      

  78.     distance = getIntent().getExtras().getInt("distance");   //获取查询范围 

  79.      

  80.     super.onCreate(savedInstanceState); 

  81.     setContentView(R.layout.location); 

  82.      

  83.     mMapView = (MapView)findViewById(R.id.bmapsView);   //初始化一个mapView  存放Map 

  84.     init();  //初始化地图管理器 

  85.     super.initMapActivity(mBMapMan); 

  86.      

  87.      

  88.     address_view = (TextView)findViewById(R.id.myLocation_id); 

  89.     SpannableStringBuilder style = new SpannableStringBuilder(String.format(getResources().getString(R.string.location_text),"位置不详")); 

  90.     style.setSpan(new ForegroundColorSpan(Color.RED), 5, style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

  91.     address_view.setText(style); 

  92.      

  93.     Button location_button = (Button)findViewById(R.id.location_button_id); 

  94.     location_button.setOnClickListener(new View.OnClickListener(){ 

  95.         @Override 

  96.         public void onClick(View v) { 

  97.              dialog = ProgressDialog.show(ShowMapAct.this, "", "数据加载中,请稍后....."); 

  98.              new Thread(new MyThread()).start(); 

  99.         } 

  100.     }); 

  101.      

  102.     mkSearch = new MKSearch();   //初始化一个MKSearch,根据location解析详细地址 

  103.     mkSearch.init(mBMapMan, this); 

  104.        mMapView.setBuiltInZoomControls(true);   //启用内置的缩放控件 

  105.        bMapController = mMapView.getController(); 

  106.        GeoPoint defaultPoint = new GeoPoint((int) (39.920934 * 1E6),(int) (116.412817 * 1E6));  //用给定的经纬度构造一个GeoPoint,单位是微度 (度 * 1E6) 

  107.        bMapController.setCenter(defaultPoint);  //设置地图中心点 

  108.        bMapController.setZoom(12);  //设置地图zoom级别 

  109.         

  110.        mkLocationManager = mBMapMan.getLocationManager(); 

  111. /**

  112. * 初始化地图管理器BMapManager

  113. */ 

  114. public void init(){ 

  115.     MapApplication app = (MapApplication)getApplication(); 

  116.        if (app.mapManager == null) { 

  117.         app.mapManager = new BMapManager(getApplication()); 

  118.         app.mapManager.init(app.mStrKey, new MapApplication.MyGeneralListener()); 

  119.        } 

  120.        mBMapMan = app.mapManager; 

  121. @Override 

  122. protected void onDestroy() { 

  123.     MapApplication app = (MapApplication)getApplication(); 

  124.     if (mBMapMan != null) { 

  125.         mBMapMan.destroy(); 

  126.         app.mapManager.destroy(); 

  127.         app.mapManager = null; 

  128.         mBMapMan = null; 

  129.     } 

  130.     super.onDestroy(); 

  131.   

  132.    @Override   

  133.    protected void onPause() {   

  134.        if (mBMapMan != null) {   

  135.            // 终止百度地图API   

  136.         mBMapMan.stop();   

  137.        }   

  138.        super.onPause();   

  139.    } 

  140.   

  141.    @Override   

  142.    protected void onResume() { 

  143.        if (mBMapMan != null) {   

  144.            // 开启百度地图API   

  145.         mBMapMan.start();   

  146.        }   

  147.        super.onResume();   

  148.    } 

  149. @Override 

  150. protected boolean isRouteDisplayed() { 

  151.     return false; 

  152. @Override 

  153. public void onGetAddrResult(MKAddrInfo result, int iError) { 

  154.     if(result==null) return; 

  155.     SpannableStringBuilder style = new SpannableStringBuilder(String.format(getResources().getString(R.string.location_text),result.strAddr)); 

  156.     style.setSpan(new ForegroundColorSpan(Color.RED), 5, style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

  157.     address_view.setText(style); 

  158.     if(dialog!=null) dialog.dismiss(); 

  159. @Override 

  160. public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {} 

  161. @Override 

  162. public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {} 

  163. @Override 

  164. public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {} 

  165. @Override 

  166. public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {} 

  167. /**

  168. * 重新定位,加载数据

  169. * @author Administrator

  170. *

  171. */ 

  172. class MyThread implements Runnable{ 

  173.     @Override 

  174.     public void run() { 

  175.         /**

  176.           * 最重要的就是这个玩意

  177.           * 由于LocationListener获取第一个位置修正的时间会很长,为了避免用户等待,

  178.           * 在LocationListener获取第一个更精确的位置之前,应当使用getLocationInfo() 获取一个缓存的位置

  179.           */ 

  180.         Location location = mkLocationManager.getLocationInfo(); 

  181.         double lat = 0d,lon = 0d; 

  182.         if(location!=null){   //定位到位置 

  183.             String coordinate = location.getLatitude()+","+location.getLongitude(); 

  184.             HotelRemoteData hotelData = new HotelRemoteData(); 

  185.             /**

  186.              * 远程获取酒店列表数据

  187.              */ 

  188.             hotelList = hotelData.getHotelToMap(coordinate,distance); 

  189.             lat = location.getLatitude(); 

  190.             lon = location.getLongitude(); 

  191.         } 

  192.          

  193.         Message msg = new Message(); 

  194.         Bundle data = new Bundle(); 

  195.         data.putDouble("lat", lat); 

  196.         data.putDouble("lon", lon); 

  197.         msg.setData(data); 

  198.         handler.sendMessage(msg); 

  199.     } 

  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. };  

原文地址:https://www.cnblogs.com/xiaochao1234/p/3738542.html