一、写一个获取方向角的类
public class MyOrientationListener implements SensorEventListener
{
private SensorManager mSensorManager;
private Context mContext;
private Sensor mSensor;
private float lastX;
public MyOrientationListener(Context context)
{
this.mContext = context;
}
@SuppressWarnings("deprecation")
public void start()
{
mSensorManager = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager != null)
{
// 获得方向传感器
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
if (mSensor != null)
{
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_UI);
}
}
public void stop()
{
mSensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
@SuppressWarnings(
{ "deprecation" })
@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)
{
if (mOnOrientationListener != null)
{
mOnOrientationListener.onOrientationChanged(x);
}
}
lastX = x;
}
}
private OnOrientationListener mOnOrientationListener;
public void setOnOrientationListener(
OnOrientationListener mOnOrientationListener)
{
this.mOnOrientationListener = mOnOrientationListener;
}
public interface OnOrientationListener
{
void onOrientationChanged(float x);
}
}
二、调用此类并获取方向角
首先初始化相关对象
//类的对象
private MyOrientationListener mMyOrientationListener;
//接受方向角
private float mCurrentX;
private Context context;
因为MyOrientationListener类是没有返回值的,我们要再写一个方法调用MyOrientationListener中的X值(方向角),并且令其为mCurrent,
private void initOrientation() {
//传感器
mMyOrientationListener = new MyOrientationListener(context);
mMyOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
@Override
public void onOrientationChanged(float x) {
mCurrentX = x;
Log.d("angle:","sda:"+mCurrentX);
}
});
}
在onCreate中将initOrientation()初始化。
三、显示当前位置和前进方向
以下代码可以实现此功能,这里我没有设置MyLocationConfiguration函数,导致我的方向角有值,但是UI一直没有变化,花了我两小时找原因,卧槽了
longitude = location.getLongitude();
latitude = location.getLatitude();
//这个就是将经纬度,方向角,传给locationBuilder,然后调用baiduMap.setMyLocationData方法实现定位功能
MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
locationBuilder.latitude(latitude);
locationBuilder.longitude(longitude);
locationBuilder.direction(mCurrentX);
MyLocationData locationData = locationBuilder.build();
baiduMap.setMyLocationData(locationData);
//必须设置成为true才能使方向指针变化,将最后的bitmapDescriptor设置为null,表示不用自定义图标
MyLocationConfiguration configuration = new
MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
true, null );
baiduMap.setMyLocationConfigeration(configuration);
下面的是MyLocationConfiguration的构造函数详细资料,我们在使用方向指针的时候一定要使enableDirection变成ture,表示允许显示方向信息
最后记住要在onCreate中声明一个this.context = context;
四、结果展示
如下图
这个图标方向角度是可以变化的,随着你的位置变化而变化,如果GPS信号差,会导致你的指针方向也不能变。