gpt4 book ai didi

Android 谷歌地图当前位置方位

转载 作者:行者123 更新时间:2023-11-29 19:30:04 25 4
gpt4 key购买 nike

我目前在 Android 上使用 Google map ,但我不确定如何旋转 map 以向用户显示当前面向的方向。

当我设置时:

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));
}

这成功地根据位置更新了 map 上的标记位置。但是,如何根据手机偏航倾斜通过旋转 map 来更改标记的朝向。

最佳答案

试试这段代码:

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);
}

关于Android 谷歌地图当前位置方位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40227427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com