我目前在Android上使用谷歌地图,但我不确定如何旋转地图以显示用户当前面对的方向。
当我设置
mMap.setMyLocationEnabled(true);
我注意到当前标记有一个小的方向箭头(当手机倾斜时,等等)。
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
CameraPosition camPos = new CameraPosition.Builder()
.target(latLng)
.zoom(16.0f)
.bearing(location.getBearing())
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
}
这成功地根据位置更新了地图上的标记位置。但是,如何根据手机的偏航倾斜,通过旋转地图来改变标记的面向方向呢?
试试下面的代码:
private SensorManager mSensorManager;
private SensorEventListener sensorEventListener;
private Sensor accelerometer;
private Sensor magnetometer;
private float[] mGravity;
private float[] mGeomagnetic;
private Float azimut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorEventListener= new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimut = orientation[0]; // orientation contains: azimut, pitch and roll
float degrees = (float) Math.toDegrees(azimut);
/**
* TRY THIS TO UPDATE YOUR CAMERA
* degrees you can use as bearing
* CameraPosition cameraPosition = new CameraPosition( myLatLng, 15, 0, degrees);
* map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),200, null);
**/
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(sensorEventListener);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
}