Search code examples
androidkotlindirection

Is there a way to set the direction of google maps according to the accelerometer?


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 !


Solution

  • 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"
    }