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

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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

近由于项目需要,研究了下百度地图定位,他们提供的实例基本都是用监听器实现自动定位的。我想实现一种效果:当用户进入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. }; 

转载于:https://my.oschina.net/u/573470/blog/143645

相关文章:

  • Swing的Look And Feel机制研究
  • html Ie 6,7,8 a超链带灰底
  • iMatrix平台核心功能——工作流管理介绍
  • 缓存、缓存算法和缓存框架简介
  • 【学习笔记10】Linux常用命令7 - 网络通信、系统关机
  • SetFileAttributes
  • “与客户的一次沟通”的所思、所虑、所得
  • Delphi Listveiw用法大全
  • apache日志存放位置(转)
  • Centos和RHEL的区别
  • Cacti监控tomcat的方法
  • clean code meaningful names
  • 从动漫产业到动漫文化
  • Android高效加载大图、多图解决方案,有效避免程序OOM
  • linux中文件颜色,蓝色,白色等各自代表的含义
  • C语言笔记(第一章:C语言编程)
  • Github访问慢解决办法
  • HashMap剖析之内部结构
  • laravel5.5 视图共享数据
  • NLPIR语义挖掘平台推动行业大数据应用服务
  • 理解 C# 泛型接口中的协变与逆变(抗变)
  • 区块链技术特点之去中心化特性
  • 如何正确配置 Ubuntu 14.04 服务器?
  • 通过几道题目学习二叉搜索树
  • 项目管理碎碎念系列之一:干系人管理
  • 怎样选择前端框架
  • - 转 Ext2.0 form使用实例
  • Spring第一个helloWorld
  • ​DB-Engines 12月数据库排名: PostgreSQL有望获得「2020年度数据库」荣誉?
  • ​ssh免密码登录设置及问题总结
  • # include “ “ 和 # include < >两者的区别
  • #13 yum、编译安装与sed命令的使用
  • (22)C#传智:复习,多态虚方法抽象类接口,静态类,String与StringBuilder,集合泛型List与Dictionary,文件类,结构与类的区别
  • (3)Dubbo启动时qos-server can not bind localhost22222错误解决
  • (Matalb时序预测)PSO-BP粒子群算法优化BP神经网络的多维时序回归预测
  • (SpringBoot)第二章:Spring创建和使用
  • (vue)页面文件上传获取:action地址
  • (安卓)跳转应用市场APP详情页的方式
  • (二)JAVA使用POI操作excel
  • (附源码)springboot炼糖厂地磅全自动控制系统 毕业设计 341357
  • (七)Java对象在Hibernate持久化层的状态
  • (一)u-boot-nand.bin的下载
  • (转)Android中使用ormlite实现持久化(一)--HelloOrmLite
  • (转)linux自定义开机启动服务和chkconfig使用方法
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .Net 8.0 新的变化
  • .net core 6 redis操作类
  • .net 生成二级域名
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .net 重复调用webservice_Java RMI 远程调用详解,优劣势说明
  • .NET6使用MiniExcel根据数据源横向导出头部标题及数据
  • .NET中使用Protobuffer 实现序列化和反序列化
  • @EnableWebMvc介绍和使用详细demo
  • @JSONField或@JsonProperty注解使用
  • @modelattribute注解用postman测试怎么传参_接口测试之问题挖掘