百度地图实现定位图标随手机方向变化而变化,即运用方向传感器
前言: 在安卓《第一行代码》里面关于百度地图sdk的学习中,发现书上的代码只实现到把自己(即定位图标)显示在地图上这一步,而图标的指向是固定的不会随手机方向改变而改变,用起来挺别扭的,故我自己查文档实现了这一功能。
具体实现:一、在书上代码的基础上,自己写一个MyOrientationListener用于监听方向传感器。
public class MyOrientationListener implements SensorEventListener {
private Context context;
private SensorManager sensorManager;
private Sensor sensor;
private float lastX; //用于记录最后一次从方向传感器获得的x值
private OnOrientationListener onOrientionListener; //内部接口实现回调
public interface OnOrientationListener{
void onOrientationChanged(float x);
}
public MyOrientationListener(Context context){
this.context=context;
}
public void setOnOrientionListener(OnOrientationListener onOrientionListener){
this.onOrientionListener=onOrientionListener;
}
@Override
public void onSensorChanged(SensorEvent event) { //手机方向改变时调用
if (event.sensor.getType()==Sensor.TYPE_ORIENTATION){
float x=event.values[SensorManager.DATA_X];
if (Math.abs(xlastX)>1.0 //设置条件防止频繁回调
{onOrientionListener.onOrientationChanged(x);
lastX=x;}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onStart(){ //获取传感器sensor并与onOrientionListener绑定
sensorManager=(SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if (sensorManager!=null){sensor=sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);}
if(sensor!=null){sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_UI);}
}
public void onStop(){
sensorManager.unregisterListener(this); //传感器解除绑定
}
}
二、在Mainactivity中初始化MyOnrientationListener
private MyOrientationListener myOrientationListener;
private double mCurrentLantitude; //此刻的纬度值
private double mCurrentLongtitude; //此刻的经度值
private int mXDirection; //此刻的x值,方向由传感器测出,范围0~360,为手机方向与北极的角度
private void initOrientationListener(){
myOrientationListener=new MyOrientationListener(getApplicationContext());
myOrientationListener.setOnOrientionListener(new MyOrientationListener.OnOrientationListener() {
@Override
public void onOrientationChanged(float x) {
mXDirection=(int)x;
// Log.d("MainActivity"," "+x);
builder=new MyLocationData.Builder();
builder.longitude(mCurrentLongtitude).latitude(mCurrentLantitude).direction(mXDirection);
data=builder.build();
baiduMap.setMyLocationData(data); //手机方向改变实时改变图标指向
MyLocationConfiguration configuration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null );
baiduMap.setMyLocationConfigeration(configuration);
}
});
}
注意:得把MyLocationConfiguration的构造函数第二个参数设置我为true才可显示方向信息,即图标方向才会改变。
三、管理传感器
protected void onStart(){
super.onStart();
myOrientationListener.onStart();}
protected void onStop(){
super.onStop();
myOrientationListener.onStop();}