Add Compass to your MapActivity

Posted: April 8, 2012 in Android Dev

package com.invp;

import com.google.android.maps.MapActivity;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.view.animation.Animation;

import android.view.animation.RotateAnimation;

import android.widget.ImageView;

import android.widget.TextView;

public class INVPMapActivity extends MapActivity implements SensorEventListener{

private SensorManager sensorManager;

private Sensor sensorOrientation;

private float azimuth = 0 ;

private float lastAzimuth = 0 ;

private TextView debugText ;

private ImageView compassView;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

debugText = (TextView)findViewById(R.id.debugText);

compassView = (ImageView)findViewById(R.id.compass);

sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

sensorOrientation = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

}

@Override

protected void onPause() {

super.onPause();

sensorManager.unregisterListener(this);

}

@Override

protected void onResume() {

super.onResume();

sensorManager.registerListener(this,sensorOrientation,SensorManager.SENSOR_DELAY_NORMAL);

}

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {

// TODO Auto-generated method stub

}

@Override

public void onSensorChanged(SensorEvent event) {

switch( event.sensor.getType() ){

case Sensor.TYPE_ORIENTATION :

float azimuthValue = event.values[0];

float pitchValue = event.values[1];

float rollValue = event.values[2];

azimuth = (azimuthValue+360)%360;

if( Math.abs(azimuth – lastAzimuth) > 5){

debugText.setText(“[“+azimuth+”]”);

rotateCompass();

}

break;

}

}

@Override

protected boolean isRouteDisplayed() {

// TODO Auto-generated method stub

return false;

}

public void rotateCompass(){

Animation compassAnim = new RotateAnimation((float)(360-lastAzimuth),(float)(360-azimuth), Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

compassAnim.setDuration(1000);

compassAnim.setRepeatCount(0);

compassAnim.setFillAfter(true);

compassView.startAnimation(compassAnim);

compassAnim=null;

lastAzimuth = azimuth;

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s