Android 百度地图 SDK v3.0.0 (二) 定位与结合方向传感器

来源:互联网 发布:专升本网络教育 编辑:程序博客网 时间:2024/06/03 10:52


在上一篇博客中,我们成功把地图导入了我们的项目。本篇我们准备为地图添加:第一,定位功能;第二,与方向传感器结合,通过旋转手机进行道路的方向确认。有了这两个功能,地图已经可以为我服务了~~~~

效果图:

好了,可以代码,为了方便,我把所有的按钮都放到了menu菜单中。
1、初次启动定位

/**      * 定位的客户端      */      private LocationClient mLocationClient;      /**      * 定位的监听器      */      public MyLocationListener mMyLocationListener;      /**      * 当前定位的模式      */      private LocationMode mCurrentMode = LocationMode.NORMAL;      /***      * 是否是第一次定位      */      private volatile boolean isFristLocation = true;      /**      * 初始化定位相关代码      */      private void initMyLocation()      {          // 定位初始化          mLocationClient = new LocationClient(this);          mMyLocationListener = new MyLocationListener();          mLocationClient.registerLocationListener(mMyLocationListener);          // 设置定位的相关配置          LocationClientOption option = new LocationClientOption();          option.setOpenGps(true);// 打开gps          option.setCoorType("bd09ll"); // 设置坐标类型          option.setScanSpan(1000);          mLocationClient.setLocOption(option);      }  

然后是定位的监听器MyLocationListener:

/**      * 实现实位回调监听      */      public class MyLocationListener implements BDLocationListener      {          @Override          public void onReceiveLocation(BDLocation location)          {              // map view 销毁后不在处理新接收的位置              if (location == null || mMapView == null)                  return;              // 构造定位数据              MyLocationData locData = new MyLocationData.Builder()                      .accuracy(location.getRadius())                      // 此处设置开发者获取到的方向信息,顺时针0-360                      .direction(mXDirection).latitude(location.getLatitude())                      .longitude(location.getLongitude()).build();              mCurrentAccracy = location.getRadius();              // 设置定位数据              mBaiduMap.setMyLocationData(locData);              mCurrentLantitude = location.getLatitude();              mCurrentLongitude = location.getLongitude();              // 设置自定义图标              BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory                      .fromResource(R.drawable.navi_map_gps_locked);              MyLocationConfigeration config = new MyLocationConfigeration(                      mCurrentMode, true, mCurrentMarker);              mBaiduMap.setMyLocationConfigeration(config);              // 第一次定位时,将地图位置移动到当前位置              if (isFristLocation)              {                  isFristLocation = false;                  LatLng ll = new LatLng(location.getLatitude(),                          location.getLongitude());                  MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);                  mBaiduMap.animateMapStatus(u);              }          }      }  

可以看到,我们初始化了定位的参数,设置了定位的监听器,每隔1s会进行一次定位,应用打开时,第一定位,会把地图中心设置当前用户位置。
定位也是比较耗电的,所以我们在onStart中开启定位,在onStop中关闭定位~~这样应用最小化时就不会一直在哪GPS请求定位了,用户要是看你app一直在那定位,估计马上就被卸载了~

@Override      protected void onStart()      {          // 开启图层定位          mBaiduMap.setMyLocationEnabled(true);          if (!mLocationClient.isStarted())          {              mLocationClient.start();          }          // 开启方向传感器          myOrientationListener.start();          super.onStart();      }      @Override      protected void onStop()      {          // 关闭图层定位          mBaiduMap.setMyLocationEnabled(false);          mLocationClient.stop();          // 关闭方向传感器          myOrientationListener.stop();          super.onStop();      }  

上面的传感器的代码,一会就会介绍~

记得在AndroidManifest.xml配一个service

<service            android:name="com.baidu.location.f"            android:enabled="true"            android:process=":remote" >            <intent-filter>                <action android:name="com.baidu.location.service_v2.2" >                </action>            </intent-filter>        </service>  

现在基本的定位功能已经实现了~不过我们还需要添加点击定位按钮和方向传感器

2、我的位置

点击我的位置菜单会调用center2myLoc方法。

case R.id.id_menu_map_myLoc:          center2myLoc();          break;  /**      * 地图移动到我的位置,此处可以重新发定位请求,然后定位;       * 直接拿最近一次经纬度,如果长时间没有定位成功,可能会显示效果不好      */      private void center2myLoc()      {          LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);          MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);          mBaiduMap.animateMapStatus(u);      }  

很简单,我们在定位的监听器中已经保存了最近一次的定位经纬度,所以只需要点击时,把地图移动到相应的位置即可。

3、集成方向传感器

首先是封装的方向传感器的类MyOrientationListener.Java

package com.zhy.zhy_baidu_ditu_demo00;  import android.content.Context;  import android.hardware.Sensor;  import android.hardware.SensorEvent;  import android.hardware.SensorEventListener;  import android.hardware.SensorManager;  public class MyOrientationListener implements SensorEventListener  {      private Context context;      private SensorManager sensorManager;      private Sensor sensor;      private float lastX ;       private OnOrientationListener onOrientationListener ;       public MyOrientationListener(Context context)      {          this.context = context;      }      // 开始      public void start()      {          // 获得传感器管理器          sensorManager = (SensorManager) context                  .getSystemService(Context.SENSOR_SERVICE);          if (sensorManager != null)          {              // 获得方向传感器              sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);          }          // 注册          if (sensor != null)          {//SensorManager.SENSOR_DELAY_UI              sensorManager.registerListener(this, sensor,                      SensorManager.SENSOR_DELAY_UI);          }      }      // 停止检测      public void stop()      {          sensorManager.unregisterListener(this);      }      @Override      public void onAccuracyChanged(Sensor sensor, int accuracy)      {      }      @Override      public void onSensorChanged(SensorEvent event)      {          // 接受方向感应器的类型            if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)            {                // 这里我们可以得到数据,然后根据需要来处理                float x = event.values[SensorManager.DATA_X];                if( Math.abs(x- lastX) > 1.0 )              {                  onOrientationListener.onOrientationChanged(x);              }  //            Log.e("DATA_X", x+"");              lastX = x ;           }        }      public void setOnOrientationListener(OnOrientationListener onOrientationListener)      {          this.onOrientationListener = onOrientationListener ;      }      public interface OnOrientationListener       {          void onOrientationChanged(float x);      }  }  

在onCreate中初始化方向传感器

/**      * 初始化方向传感器      */      private void initOritationListener()      {          myOrientationListener = new MyOrientationListener(                  getApplicationContext());          myOrientationListener                  .setOnOrientationListener(new OnOrientationListener()                  {                      @Override                      public void onOrientationChanged(float x)                      {                          mXDirection = (int) x;                          // 构造定位数据                          MyLocationData locData = new MyLocationData.Builder()                                  .accuracy(mCurrentAccracy)                                  // 此处设置开发者获取到的方向信息,顺时针0-360                                  .direction(mXDirection)                                  .latitude(mCurrentLantitude)                                  .longitude(mCurrentLongitude).build();                          // 设置定位数据                          mBaiduMap.setMyLocationData(locData);                          // 设置自定义图标                          BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory                                  .fromResource(R.drawable.navi_map_gps_locked);                          MyLocationConfigeration config = new MyLocationConfigeration(                                  mCurrentMode, true, mCurrentMarker);                          mBaiduMap.setMyLocationConfigeration(config);                      }                  });      }  

最后在onStart和onStop中分别开启和关闭方向传感器。

对于旋转手机确定方向,实际上利用了

new MyLocationData.Builder()              //此处设置开发者获取到的方向信息,顺时针0-360                                                                                                .direction(mXDirection)  

只需要把x方向的角度设置即可~是不是很简单~

好了,介绍完毕了,关闭地图样式的切换,以及跟随、罗盘等模式的切换就不介绍了,大家自己看下源码~~

0 0
原创粉丝点击