您的位置:首页 > 移动开发 > Android开发

Android百度地图,定位图标随着方向的改变而改变

2016-04-25 17:54 811 查看
代码其实很简单,用到了方向的传感器所以要用 SensorManger,具体的实现方式:

public class MyOrientationListener implements SensorEventListener {

private SensorManager mSensorManager;
private Context mContext;
private Sensor mSensor;
private float lastX;

private OnOrientationListener mOnOrientationListener;

public void setmOnOrientationListener(OnOrientationListener mOnOrientationListener) {
this.mOnOrientationListener = mOnOrientationListener;
}

public MyOrientationListener(Context context) {
this.mContext = context;
}

public void star() {
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 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;
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

public interface OnOrientationListener {
void onOrientationChanged(float x);
}
}


然后在你加载地图的activity实例化:

private MyOrientationListener myOrientationListener;

//方向传感器
myOrientationListener = new MyOrientationListener(this);
myOrientationListener.setmOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
@Override
public void onOrientationChanged(float x) {
mCurrentX = x;
}
});


activity重写 start()和stop()方法:

@Override
protected void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();

//开启定位的允许
myBaiduMap.setMyLocationEnabled(true);
if (!mLocationClient.isStarted()) {
mLocationClient.start();
//开启方向传感器
myOrientationListener.star();
}
}

@Override
protected void onStop() {
super.onStop();
//关闭定位
myBaiduMap.setMyLocationEnabled(false);
mLocationClient.stop();
//停止方向传感器
myOrientationListener.stop();
client.disconnect();
}


这就是所有的代码了,是不是很简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息