0

I would like to know if there is a way of using the accelerometer of an Android device in order to set the direction of the displayed Google Maps ?

Here is how I get a reference to the Accelerometer :

val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
val sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
if (sensorAccelerometer != null) sensorManager.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL)


override fun onSensorChanged(event: SensorEvent?) {
    if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER){
        Log.d(TAG, "onSensorChanger ACCELEROMETER")
        val accelX = event.values[0]
        val accelY = event.values[1]
        val accelZ = event.values[2]

        textViewAdView.text = "aX=${accelX.toString()}\r\naY=${accelY.toString()}\r\naZ=${accelZ.toString()}"
     }
}

Thanks !

KotlinIsland
  • 799
  • 1
  • 6
  • 25

2 Answers2

1

You can just show the user's current location and direction of movement using googleMap.setMyLocationEnabled(true);

But if you want to turn the whole map, you can use updateCameraBearing():

https://stackoverflow.com/a/37486292/7434090

Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
0

I already use this feature with the following Kotlin code :

override fun onMapReady(googleMap: GoogleMap) {

    mMap = googleMap
    mMap.uiSettings.isCompassEnabled = true
    mMap.uiSettings.isMapToolbarEnabled = true
    mMap.uiSettings.isMyLocationButtonEnabled = true
    try {
        mMap.isMyLocationEnabled = true
    }catch (e: SecurityException) {
    }

}

I'll check the bearing stuff, thanks

I will try this when outside :

When getting a new location from a fusedLocationClient :

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
...
updateCamera(location.bearing)
....
private fun updateCamera(bearing : Float) {
    val oldPos = mMap.getCameraPosition()
    val pos = CameraPosition.builder(oldPos).bearing(bearing).build()
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(pos))

    textViewAdView.text = "Bearing=$bearing"
}
KotlinIsland
  • 799
  • 1
  • 6
  • 25