当前位置: 首页 > news >正文

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.    

  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. @Override 

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

  11. public void onTerminate() { 

  12.     // TODO Auto-generated method stub 

  13.     if(mapManager != null) 

  14.     { 

  15.         mapManager.destroy(); 

  16.         mapManager = null; 

  17.     } 

  18.     super.onTerminate(); 

  19.  

  20. static class MyGeneralListener implements MKGeneralListener{ 

  21.  

  22.     @Override 

  23.     public void onGetNetworkState(int arg0) { 

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

  25.                 Toast.LENGTH_LONG).show(); 

  26.     } 

  27.     @Override 

  28.     public void onGetPermissionState(int iError) { 

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

  30.             // 授权Key错误: 

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

  32.                     Toast.LENGTH_LONG).show(); 

  33.         } 

  34.     } 

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

  36.  

  37.        private BMapManager mBMapMan = null; 

  38. private MapView mMapView = null; 

  39. private MapController bMapController; 

  40. private MKLocationManager mkLocationManager; 

  41. private MKSearch mkSearch; 

  42.  

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

  44.  

  45. private ProgressDialog dialog; 

  46. private List<HotelInfo> hotelList; 

  47.  

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

  49.  

  50.    Handler handler = new Handler(){ 

  51.     @Override 

  52.     public void handleMessage(Message msg) { 

  53.          

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

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

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

  57.             GeoPoint point = new GeoPoint( 

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

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

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

  61.             bMapController.setZoom(15); 

  62.              

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

  64.              

  65.             MyLocationOverlay myLoc = new MyLocationOverlayFromMap(ShowMapAct.this,mMapView); 

  66.             myLoc.enableMyLocation();   // 启用定位 

  67.             myLoc.enableCompass();      // 启用指南针 

  68.             mMapView.getOverlays().add(myLoc); 

  69.         }else{ 

  70.             Toast.makeText(ShowMapAct.this, "没有加载到您的位置", Toast.LENGTH_LONG).show(); 

  71.         } 

  72.          

  73.         if(hotelList!=null){ 

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

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

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

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

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

  79.         } 

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

  81.     } 

  82.   }; 

  83.  

  84. @Override 

  85. protected void onCreate(Bundle savedInstanceState) { 

  86.      

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

  88.      

  89.     super.onCreate(savedInstanceState); 

  90.     setContentView(R.layout.location); 

  91.      

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

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

  94.     super.initMapActivity(mBMapMan); 

  95.      

  96.      

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

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

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

  100.     address_view.setText(style); 

  101.      

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

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

  104.         @Override 

  105.         public void onClick(View v) { 

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

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

  108.         } 

  109.     }); 

  110.      

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

  112.     mkSearch.init(mBMapMan, this); 

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

  114.        bMapController = mMapView.getController(); 

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

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

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

  118.         

  119.        mkLocationManager = mBMapMan.getLocationManager(); 

  120. /**

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

  122. */ 

  123. public void init(){ 

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

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

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

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

  128.        } 

  129.        mBMapMan = app.mapManager; 

  130.  

  131. @Override 

  132. protected void onDestroy() { 

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

  134.     if (mBMapMan != null) { 

  135.         mBMapMan.destroy(); 

  136.         app.mapManager.destroy(); 

  137.         app.mapManager = null; 

  138.         mBMapMan = null; 

  139.     } 

  140.     super.onDestroy(); 

  141.  

  142.   

  143.    @Override   

  144.    protected void onPause() {   

  145.        if (mBMapMan != null) {   

  146.            // 终止百度地图API   

  147.         mBMapMan.stop();   

  148.        }   

  149.        super.onPause();   

  150.    } 

  151.   

  152.    @Override   

  153.    protected void onResume() { 

  154.        if (mBMapMan != null) {   

  155.            // 开启百度地图API   

  156.         mBMapMan.start();   

  157.        }   

  158.        super.onResume();   

  159.    } 

  160.  

  161. @Override 

  162. protected boolean isRouteDisplayed() { 

  163.     return false; 

  164.  

  165. @Override 

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

  167.     if(result==null) return; 

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

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

  170.     address_view.setText(style); 

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

  172.  

  173. @Override 

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

  175. @Override 

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

  177. @Override 

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

  179. @Override 

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

  181.  

  182. /**

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

  184. * @author Administrator

  185. *

  186. */ 

  187. class MyThread implements Runnable{ 

  188.     @Override 

  189.     public void run() { 

  190.         /**

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

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

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

  194.           */ 

  195.         Location location = mkLocationManager.getLocationInfo(); 

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

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

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

  199.             HotelRemoteData hotelData = new HotelRemoteData(); 

  200.             /**

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

  202.              */ 

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

  204.             lat = location.getLatitude(); 

  205.             lon = location.getLongitude(); 

  206.         } 

  207.          

  208.         Message msg = new Message(); 

  209.         Bundle data = new Bundle(); 

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

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

  212.         msg.setData(data); 

  213.         handler.sendMessage(msg); 

  214.     } 

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

     

相关文章:

  • Nagios 监控温度感应器
  • 转:第二次重置OPPO手机官网任意账户密码(秒改)
  • Django 多数据操作 router 方法
  • java设计模式_代理模式
  • Gradle 取相对路径
  • VIEW登陆故障解决办法。
  • 有规律的坚持写文章有多难?
  • log4j+commons-logging结合使用
  • java每日小算法(20)
  • Dive into Python
  • ORA-00600错误及其解决方案
  • java-第二章-华氏温度转摄氏温度
  • jprofile学习资料
  • OpenGL基础图形编程 - 复杂物体建模
  • 几道经典C语言面试题
  • 【翻译】Mashape是如何管理15000个API和微服务的(三)
  • C++类的相互关联
  • export和import的用法总结
  • Java|序列化异常StreamCorruptedException的解决方法
  • JDK 6和JDK 7中的substring()方法
  • js
  • MySQL用户中的%到底包不包括localhost?
  • WinRAR存在严重的安全漏洞影响5亿用户
  • Yii源码解读-服务定位器(Service Locator)
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 代理模式
  • 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频
  • 对超线程几个不同角度的解释
  • 计算机在识别图像时“看到”了什么?
  • 前端技术周刊 2019-02-11 Serverless
  • 容器服务kubernetes弹性伸缩高级用法
  • 如何使用 OAuth 2.0 将 LinkedIn 集成入 iOS 应用
  • 入手阿里云新服务器的部署NODE
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 我感觉这是史上最牛的防sql注入方法类
  • 一天一个设计模式之JS实现——适配器模式
  • 一文看透浏览器架构
  • 在Mac OS X上安装 Ruby运行环境
  • python最赚钱的4个方向,你最心动的是哪个?
  • 如何在招聘中考核.NET架构师
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • ​LeetCode解法汇总2808. 使循环数组所有元素相等的最少秒数
  • #宝哥教你#查看jquery绑定的事件函数
  • (+3)1.3敏捷宣言与敏捷过程的特点
  • (01)ORB-SLAM2源码无死角解析-(66) BA优化(g2o)→闭环线程:Optimizer::GlobalBundleAdjustemnt→全局优化
  • (C#)Windows Shell 外壳编程系列9 - QueryInfo 扩展提示
  • (二)丶RabbitMQ的六大核心
  • (附源码)springboot工单管理系统 毕业设计 964158
  • (附源码)springboot教学评价 毕业设计 641310
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • (转)人的集合论——移山之道
  • .net 4.0发布后不能正常显示图片问题
  • .NET/C# 利用 Walterlv.WeakEvents 高性能地定义和使用弱事件
  • @AutoConfigurationPackage的使用
  • @RequestMapping用法详解