IAmGroot
IAmGroot

Reputation: 13855

Android Device (GPS) Direction

Using Location.getBearing(); I seem to get randomly changing bearings.

Aka, I can turn the device around slowly and it wont notice, it just chooses its own random bearings.

I know the device is working, as the "You are here" icon in the Maps app on the tablet slowly rotates as I rotate the device.

Is there a different proper way of getting bearing? I am using the GPS. Maybe there is a better way to determine which direction you are facing.

Upvotes: 6

Views: 11476

Answers (3)

IAmGroot
IAmGroot

Reputation: 13855

Following from herom's answer using the link: http://android-coding.blogspot.co.at/2012/03/create-our-android-compass.html

I extended my class to implement the sensor: extends Activity implements SensorEventListener

And implemented as suggested, but modified it to take into account, the orientation of the screen.

Here is the code I went with:

@Override
public void onSensorChanged(SensorEvent event) {
    switch(event.sensor.getType()){
    case Sensor.TYPE_ACCELEROMETER:
        for(int i =0; i < 3; i++){
            valuesAccelerometer[i] = event.values[i];
        }
        break;
    case Sensor.TYPE_MAGNETIC_FIELD:
        for(int i =0; i < 3; i++){
            valuesMagneticField[i] = event.values[i];
        }
        break;
    }

    boolean success = SensorManager.getRotationMatrix(
            matrixR,
            matrixI,
            valuesAccelerometer,
            valuesMagneticField);

    if(success){
        SensorManager.getOrientation(matrixR, matrixValues);

        double azimuth = Math.toDegrees(matrixValues[0]);
        //double pitch = Math.toDegrees(matrixValues[1]);
        //double roll = Math.toDegrees(matrixValues[2]);

        WindowManager mWindowManager =  (WindowManager) getSystemService(WINDOW_SERVICE);
        Display mDisplay = mWindowManager.getDefaultDisplay();

        Float degToAdd = 0f;

        if(mDisplay.getRotation() == Surface.ROTATION_0)
            degToAdd = 0.0f;
        if(mDisplay.getRotation() == Surface.ROTATION_90)
            degToAdd = 90.0f;
        if(mDisplay.getRotation() == Surface.ROTATION_180)
            degToAdd = 180.0f;
        if(mDisplay.getRotation() == Surface.ROTATION_270)
            degToAdd = 270.0f;

        mapView.setFacingDirection((float) (azimuth + degToAdd)); //DEGREES NOT RADIANS
    }
}

Upvotes: 0

Adam Monos
Adam Monos

Reputation: 4297

The Location.getBearing() returns the bearing that the GPS satellites computed for you. It is not a real time representation of the heading of your device. The Google Maps app uses the device's built in G-sensors to get the direction you are facing.

Upvotes: 3

herom
herom

Reputation: 2542

Try to get bearing from Accelerometer sensor and Magnetic Field (G-) sensor.

Here's a tutorial: http://android-coding.blogspot.co.at/2012/03/create-our-android-compass.html

Upvotes: 3

Related Questions