aleph_null aleph_null -3 years ago 122
Android Question

android maps auto-rotate

If you open the Google maps app, there is a button on the top right of the screen that you can press to center the map on your current location. The button's icon then changes. If you press the same button again, the map auto-rotates based on your compass heading. In other words, the map becomes egocentric (as opposed to allocentric AKA north always up).

Google recently launched maps API V2 for Android and I certainly like it more than the old one. By default, android maps V2 will include the "center on location" button. However, pressing it more than once does not enable auto-rotation; it merely tries to center the map on your location again.

Does anyone know how I can auto-rotate the map using maps API v2 just like the google maps app does? Will I have to implement this functionality myself or is it in the API and i'm just not seeing it? I appreciate all help.

Answer Source

Ok here's how I think it should be done a year later. Please correct me if you spot any issues.

Most of the following code deals with a discrepancy between coordinate systems. I'm using a rotation vector sensor. From the docs: Y is tangential to the ground at the device's current location and points towards magnetic north. Bearing in google maps, on the other hand, seems to point to true north. this page shows how the conversion is done

1) get the current declination from your current GPS location

public void onLocationChanged(Location location) {
    GeomagneticField field = new GeomagneticField(

    // getDeclination returns degrees
    mDeclination = field.getDeclination();

2) calculate bearing from declination and magnetic north

public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
                mRotationMatrix , event.values);
        float[] orientation = new float[3];
        SensorManager.getOrientation(mRotationMatrix, orientation);
        float bearing = Math.toDegrees(orientation[0]) + mDeclination;

3) update maps

private void updateCamera(float bearing) {
    CameraPosition oldPos = mMap.getCameraPosition();

    CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing).build();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download