Updated Compat library and cleaned up code

Signed-off-by: Ricky Barrette <rickbarrette@gmail.com>
This commit is contained in:
2012-07-01 11:19:46 -04:00
parent 2abc43c3bf
commit 39cc29a4c5
33 changed files with 1532 additions and 1548 deletions

View File

@@ -15,8 +15,8 @@
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-sdk <uses-sdk
android:minSdkVersion="4" android:minSdkVersion="8"
android:targetSdkVersion="11" /> android:targetSdkVersion="15" />
<uses-feature <uses-feature
android:name="android.hardware.location" android:name="android.hardware.location"

Binary file not shown.

Binary file not shown.

View File

@@ -1,22 +1,23 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:orientation="vertical" >
android:orientation="vertical">
<TextView <TextView
android:id="@+id/TextView01" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="20dip" android:textColor="#000000"
android:textColor="#000000"/> android:textSize="20dip" />
<TextView
android:id="@+id/TextView02" <TextView
android:layout_width="wrap_content" android:id="@+id/TextView02"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:textSize="20dip" android:layout_height="wrap_content"
android:textColor="#000000" android:layout_gravity="right"
android:layout_gravity="right" android:paddingRight="10dip"
android:paddingRight="10dip" android:textColor="#000000"
/> android:textSize="20dip" />
</LinearLayout> </LinearLayout>

View File

@@ -4,7 +4,7 @@
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:background="#ffffff" android:background="#ffffff"
tools:ignore="ContentDescription" > tools:ignore="ContentDescription,Overdraw" >
<ImageView <ImageView
android:id="@+id/skyhook_img" android:id="@+id/skyhook_img"

View File

@@ -26,22 +26,40 @@ import com.skyhookwireless.wps.XPS;
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHook implements GeoPointLocationListener{ public class SkyHook implements GeoPointLocationListener{
private class XPScallback implements WPSPeriodicLocationCallback {
@Override
public void done() {
mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE));
}
@Override
public WPSContinuation handleError(final WPSReturnCode error) {
mHandler.sendMessage(mHandler.obtainMessage(ERROR_MESSAGE, error));
return WPSContinuation.WPS_CONTINUE;
}
@Override
public WPSContinuation handleWPSPeriodicLocation(final WPSLocation location) {
mHandler.sendMessage(mHandler.obtainMessage(LOCATION_MESSAGE, location));
return WPSContinuation.WPS_CONTINUE;
}
}
public static final String TAG = "Skyhook"; public static final String TAG = "Skyhook";
public static final String USERNAME = "cjyh95q32gsc"; public static final String USERNAME = "cjyh95q32gsc";
public static final String USERNAME_FOR_TESTING = "twentycodes"; public static final String USERNAME_FOR_TESTING = "twentycodes";
public static final String REALM = "TwentyCodes"; public static final String REALM = "TwentyCodes";
public static final int LOCATION_MESSAGE = 1; public static final int LOCATION_MESSAGE = 1;
public static final int ERROR_MESSAGE = 2; public static final int ERROR_MESSAGE = 2;
public static final int DONE_MESSAGE = 3; public static final int DONE_MESSAGE = 3;
private final XPScallback mXPScallback = new XPScallback(); private final XPScallback mXPScallback = new XPScallback();
private final XPS mXps; private final XPS mXps;
private final Context mContext; private final Context mContext;
private GeoPointLocationListener mListener; private GeoPointLocationListener mListener;
private long mPeriod = 0l; //period is in milliseconds for periodic updates private long mPeriod = 0l; //period is in milliseconds for periodic updates
private int mIterations = 0; private final int mIterations = 0;
private WPSAuthentication mWPSAuthentication; private WPSAuthentication mWPSAuthentication;
private Handler mHandler; private static Handler mHandler;
private boolean isPeriodicEnabled; private boolean isPeriodicEnabled;
private boolean hasLocation; private boolean hasLocation;
protected AndroidGPS mSkyHookFallback = null; protected AndroidGPS mSkyHookFallback = null;
@@ -49,95 +67,79 @@ public class SkyHook implements GeoPointLocationListener{
private boolean isFallBackScheduled = false; private boolean isFallBackScheduled = false;
private boolean isEnabled = false; private boolean isEnabled = false;
private boolean isUnauthorized = false; private boolean isUnauthorized = false;
private boolean isFirstFix; private boolean isFirstFix;
/* /*
* this runnable will be used to check if we have location from skyhook, * this runnable will be used to check if we have location from skyhook,
* if we dont, then we will us android's location services to fall back on. * if we dont, then we will us android's location services to fall back on.
*/ */
private final Runnable mFallBack = new Runnable() { private final Runnable mFallBack = new Runnable() {
@Override
public void run() { public void run() {
mHandler.removeCallbacks(mFallBack); mHandler.removeCallbacks(mFallBack);
Log.d(TAG,"skyhook, "+ (hasLocation ? "is" : "isn't") +" working!"); Log.d(TAG,"skyhook, "+ (hasLocation ? "is" : "isn't") +" working!");
if((! hasLocation) && (mSkyHookFallback == null) && isEnabled){ if(! hasLocation && mSkyHookFallback == null && isEnabled){
Log.d(TAG,"falling back on android"); Log.d(TAG,"falling back on android");
mSkyHookFallback = new AndroidGPS(mContext); mSkyHookFallback = new AndroidGPS(mContext);
mSkyHookFallback.enableLocationUpdates(SkyHook.this); mSkyHookFallback.enableLocationUpdates(SkyHook.this);
/* /*
* Schedule another check, if skyhook is still enabled * Schedule another check, if skyhook is still enabled
*/ */
if(mXps != null) if(mXps != null)
mHandler.postDelayed(mFallBack, mFallBackDelay ); mHandler.postDelayed(mFallBack, mFallBackDelay );
} else { } else {
Log.d(TAG,"already fell back on android"); Log.d(TAG,"already fell back on android");
if(mSkyHookFallback != null) { if(mSkyHookFallback != null) {
Log.d(TAG,"got location, picking up the slack"); Log.d(TAG,"got location, picking up the slack");
mSkyHookFallback.disableLocationUpdates(); mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null; mSkyHookFallback = null;
} }
isFallBackScheduled = false; isFallBackScheduled = false;
} }
} }
}; };
/* /*
* this runnable keeps skyhook working! * this runnable keeps skyhook working!
*/ */
private final Runnable mPeriodicUpdates = new Runnable() { private final Runnable mPeriodicUpdates = new Runnable() {
@Override
public void run() { public void run() {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG,"geting location"); Log.d(TAG,"geting location");
mXps.getXPSLocation(mWPSAuthentication, mIterations, XPS.EXACT_ACCURACY, mXPScallback); mXps.getXPSLocation(mWPSAuthentication, mIterations, XPS.EXACT_ACCURACY, mXPScallback);
}
};
private class XPScallback implements WPSPeriodicLocationCallback {
@Override
public void done() {
mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE));
} }
};
@Override
public WPSContinuation handleError(WPSReturnCode error) {
mHandler.sendMessage(mHandler.obtainMessage(ERROR_MESSAGE, error));
return WPSContinuation.WPS_CONTINUE;
}
@Override
public WPSContinuation handleWPSPeriodicLocation(WPSLocation location) {
mHandler.sendMessage(mHandler.obtainMessage(LOCATION_MESSAGE, location));
return WPSContinuation.WPS_CONTINUE;
}
}
/** /**
* Constructors a new skyhook object * Constructors a new skyhook object
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHook(Context context) { public SkyHook(final Context context) {
mXps = new XPS(context); mXps = new XPS(context);
mContext = context; mContext = context;
// initialize the Handler which will display location data // initialize the Handler which will display location data
// in the text view. we use a Handler because UI updates // in the text view. we use a Handler because UI updates
// must occur in the UI thread // must occur in the UI thread
setUIHandler(); setUIHandler();
isFirstFix = true; isFirstFix = true;
} }
/** /**
* Constructors a new skyhook object * Constructors a new skyhook object
* @param context * @param context
* @param period between location updates in milliseconds * @param period between location updates in milliseconds
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHook(Context context, long period) { public SkyHook(final Context context, final long period) {
this(context); this(context);
mPeriod = period; mPeriod = period;
} }
/** /**
* request current user location, note that the listeners onLocationChanged() will be call multiple times. * request current user location, note that the listeners onLocationChanged() will be call multiple times.
* updates will stop once an accurate location is determined. * updates will stop once an accurate location is determined.
@@ -150,7 +152,7 @@ public class SkyHook implements GeoPointLocationListener{
mHandler.post(mPeriodicUpdates); mHandler.post(mPeriodicUpdates);
} }
} }
/** /**
* Attempts to register the the listener for periodic updates * Attempts to register the the listener for periodic updates
* @author Ricky Barrette * @author Ricky Barrette
@@ -158,17 +160,17 @@ public class SkyHook implements GeoPointLocationListener{
public void getUpdates(){ public void getUpdates(){
Log.d(TAG,"getUpdates()"); Log.d(TAG,"getUpdates()");
if (mListener != null) { if (mListener != null) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.i(TAG, "username: " + SkyHookRegistration.getUserName(mContext)); Log.i(TAG, "username: " + SkyHookRegistration.getUserName(mContext));
mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM); mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM);
isPeriodicEnabled = true; isPeriodicEnabled = true;
mHandler.post(mPeriodicUpdates); mHandler.post(mPeriodicUpdates);
isEnabled = true; isEnabled = true;
} }
} }
/** /**
* @return true is skyhook is enabled * @return true is skyhook is enabled
* @author ricky barrette * @author ricky barrette
@@ -176,129 +178,127 @@ public class SkyHook implements GeoPointLocationListener{
public boolean isEnabled(){ public boolean isEnabled(){
return isEnabled; return isEnabled;
} }
@Override
public void onFirstFix(final boolean firstFix) {
if(mListener != null)
mListener.onFirstFix(firstFix);
}
/** /**
* Removes any current registration for location updates of the current activity * called from our skyhook to android fall back class
* with the given LocationListener. Following this call, updates will no longer * (non-Javadoc)
* occur for this listener. * @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint, int)
* @author ricky barrette
*/
@Override
public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(! hasLocation)
if(mListener != null)
mListener.onLocationChanged(point, accuracy);
}
/**
* Removes any current registration for location updates of the current activity
* with the given LocationListener. Following this call, updates will no longer
* occur for this listener.
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void removeUpdates() { public void removeUpdates() {
Log.d(TAG,"removeUpdates()"); Log.d(TAG,"removeUpdates()");
mHandler.removeCallbacks(mFallBack); mHandler.removeCallbacks(mFallBack);
mListener = null; mListener = null;
isPeriodicEnabled = false; isPeriodicEnabled = false;
if(mXps != null) if(mXps != null)
mXps.abort(); mXps.abort();
if(mSkyHookFallback != null) { if(mSkyHookFallback != null) {
Log.d(TAG,"disabling fallback"); Log.d(TAG,"disabling fallback");
mSkyHookFallback.disableLocationUpdates(); mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null; mSkyHookFallback = null;
isEnabled = false; isEnabled = false;
} }
isFirstFix = true; isFirstFix = true;
} }
/** /**
* Used for receiving notifications from SkyHook when * Used for receiving notifications from SkyHook when
* the location has changed. These methods are called if the * the location has changed. These methods are called if the
* LocationListener has been registered with the location manager service using the method. * LocationListener has been registered with the location manager service using the method.
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocationListener(GeoPointLocationListener listener){ public void setLocationListener(final GeoPointLocationListener listener){
Log.d(TAG,"setLocationListener()"); Log.d(TAG,"setLocationListener()");
if (mListener == null) { if (mListener == null)
mListener = listener; mListener = listener;
}
} }
private void setUIHandler() { private void setUIHandler() {
mHandler = new Handler() { mHandler = new Handler() {
@Override @Override
public void handleMessage(final Message msg) { public void handleMessage(final Message msg) {
switch (msg.what) { switch (msg.what) {
case LOCATION_MESSAGE: case LOCATION_MESSAGE:
if (msg.obj instanceof WPSLocation) { if (msg.obj instanceof WPSLocation) {
WPSLocation location = (WPSLocation) msg.obj; final WPSLocation location = (WPSLocation) msg.obj;
if (mListener != null && location != null) { if (mListener != null && location != null) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG,"got location "+ location.getLatitude() +", "+ location.getLongitude()+" +- "+ location.getHPE() +"m"); Log.d(TAG,"got location "+ location.getLatitude() +", "+ location.getLongitude()+" +- "+ location.getHPE() +"m");
mListener.onLocationChanged(new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), location.getHPE()); mListener.onLocationChanged(new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), location.getHPE());
mListener.onFirstFix(isFirstFix); mListener.onFirstFix(isFirstFix);
hasLocation = true; hasLocation = true;
isFirstFix = false; isFirstFix = false;
} }
} }
return; return;
case ERROR_MESSAGE:
if( msg.obj instanceof WPSReturnCode) {
WPSReturnCode code = (WPSReturnCode) msg.obj;
if ( code != null){
Log.w(TAG, code.toString());
}
hasLocation = false;
/*
* check to see if the error returned is an WPS_ERROR_UNAUTHORIZED
* then check to see if this is the second occurrence of WPS_ERROR_UNAUTHORIZED,
* if so we will stop skyhook's services to cut down the work load
*/
if(code == WPSReturnCode.WPS_ERROR_UNAUTHORIZED){
if (isUnauthorized){
isPeriodicEnabled = false;
mXps.abort();
// mXps = null;
}
isUnauthorized = true;
}
/*
* check to see if we already have a fall back Scheduled
* if we dont, and there is not fallback already in place, then schedule one
*/
if((! isFallBackScheduled) && ( mSkyHookFallback == null) && isEnabled) {
Log.d(TAG, "scheduling fallback");
mHandler.postDelayed(mFallBack, mFallBackDelay);
isFallBackScheduled = true;
}
}
return;
case DONE_MESSAGE:
if (isPeriodicEnabled) {
mHandler.postDelayed(mPeriodicUpdates, mPeriod);
Log.d(TAG,"done getting location");
}
return;
}
}
};
}
/** case ERROR_MESSAGE:
* called from our skyhook to android fall back class if( msg.obj instanceof WPSReturnCode) {
* (non-Javadoc) final WPSReturnCode code = (WPSReturnCode) msg.obj;
* @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint, int) if ( code != null)
* @author ricky barrette Log.w(TAG, code.toString());
*/ hasLocation = false;
@Override
public void onLocationChanged(GeoPoint point, int accuracy) {
if(! hasLocation)
if(mListener != null)
mListener.onLocationChanged(point, accuracy);
}
@Override /*
public void onFirstFix(boolean firstFix) { * check to see if the error returned is an WPS_ERROR_UNAUTHORIZED
if(mListener != null) * then check to see if this is the second occurrence of WPS_ERROR_UNAUTHORIZED,
mListener.onFirstFix(firstFix); * if so we will stop skyhook's services to cut down the work load
*/
if(code == WPSReturnCode.WPS_ERROR_UNAUTHORIZED){
if (isUnauthorized){
isPeriodicEnabled = false;
mXps.abort();
// mXps = null;
}
isUnauthorized = true;
}
/*
* check to see if we already have a fall back Scheduled
* if we dont, and there is not fallback already in place, then schedule one
*/
if(! isFallBackScheduled && mSkyHookFallback == null && isEnabled) {
Log.d(TAG, "scheduling fallback");
postDelayed(mFallBack, mFallBackDelay);
isFallBackScheduled = true;
}
}
return;
case DONE_MESSAGE:
if (isPeriodicEnabled) {
postDelayed(mPeriodicUpdates, mPeriod);
Log.d(TAG,"done getting location");
}
return;
}
}
};
} }
} }

View File

@@ -20,11 +20,36 @@ import com.skyhookwireless.wps.XPS;
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHookRegistration{ public class SkyHookRegistration{
/**
* returns the users username
* @param context
* @return
* @author ricky barrette
*/
public static String getUserName(final Context context){
switch(LocationLibraryConstants.DEFAULT_REGISTRATION_BEHAVIOR){
case NORMAL:
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null");
return tm.getLine1Number();
case RETURN_NULL:
return null;
case USE_TESTING_USERNAME:
return SkyHook.USERNAME_FOR_TESTING;
}
return null;
}
private final XPS mXps; private final XPS mXps;
private final Context mContext; private final Context mContext;
public SkyHookRegistration(Context context){ public SkyHookRegistration(final Context context){
mContext = context; mContext = context;
mXps = new XPS(context); mXps = new XPS(context);
} }
@@ -32,7 +57,7 @@ public class SkyHookRegistration{
/** /**
* attempts to register the user by their cell # * attempts to register the user by their cell #
* *
* TODO hash cell number for privacy * TODO hash cell number for privacy
* @param listener for call back methods * @param listener for call back methods
* @author ricky barrette * @author ricky barrette
*/ */
@@ -41,40 +66,14 @@ public class SkyHookRegistration{
final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null) if(tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null"); Log.v(SkyHook.TAG, "TelephonyManager is null");
String newUser = tm.getLine1Number(); final String newUser = tm.getLine1Number();
if(Debug.DEBUG) if(Debug.DEBUG)
Log.v(SkyHook.TAG, "newUser = " + newUser); Log.v(SkyHook.TAG, "newUser = " + newUser);
if(newUser == null) { if(newUser == null)
Log.e(SkyHook.TAG,"users number is null"); Log.e(SkyHook.TAG,"users number is null");
}
mXps.registerUser(new WPSAuthentication(SkyHook.USERNAME, SkyHook.REALM), new WPSAuthentication(newUser, SkyHook.REALM), listener); mXps.registerUser(new WPSAuthentication(SkyHook.USERNAME, SkyHook.REALM), new WPSAuthentication(newUser, SkyHook.REALM), listener);
} }
} }
/**
* returns the users username
* @param context
* @return
* @author ricky barrette
*/
public static String getUserName(final Context context){
switch(LocationLibraryConstants.DEFAULT_REGISTRATION_BEHAVIOR){
case NORMAL:
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null");
return tm.getLine1Number();
case RETURN_NULL:
return null;
case USE_TESTING_USERNAME:
return SkyHook.USERNAME_FOR_TESTING;
}
return null;
}
} }

View File

@@ -37,147 +37,9 @@ import com.skyhookwireless.wps.WPSReturnCode;
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHookService extends Service implements GeoPointLocationListener, RegistrationCallback{ public class SkyHookService extends Service implements GeoPointLocationListener, RegistrationCallback{
public static final String TAG = "SkyHookService"; public static final String TAG = "SkyHookService";
public static final int REQUEST_CODE = 32741942; public static final int REQUEST_CODE = 32741942;
private SkyHook mSkyhook;
protected long mPeriod = -1;
private GeoPoint mLocation;
private int mStartID;
private int mRequiredAccuracy;
private Intent mIntent;
private int mAccuracy;
/**
* broadcasts location to anything listening for updates
*
* @author ricky barrette
*/
private void braodcastLocation() {
if (mLocation != null) {
Intent locationUpdate = new Intent();
if(mIntent.getAction() != null)
locationUpdate.setAction(mIntent.getAction());
else
locationUpdate.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE);
locationUpdate.putExtra(LocationManager.KEY_LOCATION_CHANGED, convertLocation());
sendBroadcast(locationUpdate);
}
}
/**
* converts skyhook's location object into android's location object
* @return converted location
* @author ricky barrette
*/
public Location convertLocation(){
Location location = new Location("location");
location.setLatitude(this.mLocation.getLatitudeE6() /1e6);
location.setLongitude(this.mLocation.getLongitudeE6() /1e6);
location.setAccuracy(this.mAccuracy);
return location;
}
/**
* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
* @param arg0
* @return
* @author Ricky Barrette barrette
*/
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate(){
super.onCreate();
this.mSkyhook = new SkyHook(this);
this.mSkyhook.setLocationListener(this);
/*
* fail safe
* this will stop the service after the maximum running time, if location has not been reported
*/
new Handler().postDelayed(new Runnable(){
@Override
public void run(){
stopSelfResult(mStartID);
}
}, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME);
}
/**
* aborts location services
* (non-Javadoc)
* @see android.app.Service#onDestroy()
* @author Ricky Barrette
*/
@Override
public void onDestroy(){
mSkyhook.removeUpdates();
braodcastLocation();
//ask android to restart service if mPeriod is set
if(mPeriod > -1)
registerWakeUp();
super.onDestroy();
}
/*
* I believe that this method is no longer needed as we are not supporting pre 2.1
*/
// /**
// * To keep backwards compatibility we override onStart which is the equivalent of onStartCommand in pre android 2.x
// * @author ricky barrette
// */
// @Override
// public void onStart(Intent intent, int startId) {
// Log.i(SkyHook.TAG, "onStart.Service started with start id of: " + startId);
// parseIntent(intent);
// this.mSkyhook.getUpdates();
// }
/**
* This method is called when startService is called. only used in 2.x android.
* @author ricky barrette
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(SkyHook.TAG , "onStartCommand.Service started with start id of: " + startId);
mStartID = startId;
parseIntent(intent);
this.mSkyhook.getUpdates();
return START_STICKY;
}
/**
* Parses the incoming intent for the service options
*
* @author ricky barrette
*/
private void parseIntent(Intent intent){
this.mIntent = intent;
if(intent != null){
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES))
mPeriod = intent.getLongExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, LocationLibraryConstants.FAIL_SAFE_UPDATE_INVERVAL);
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY))
mRequiredAccuracy = intent.getIntExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY, LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY);
}
}
/**
* registers our Receiver the starts the service with the alarm manager
* @author ricky barrette
*/
private void registerWakeUp(){
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + this.mPeriod, PendingIntent.getService(this, REQUEST_CODE, this.mIntent, 0));
}
/** /**
* a convince method for getting an intent to start the service * a convince method for getting an intent to start the service
* @param context * @param context
@@ -187,7 +49,6 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
public static Intent getStartServiceIntent(final Context context){ public static Intent getStartServiceIntent(final Context context){
return new Intent(context, SkyHookService.class); return new Intent(context, SkyHookService.class);
} }
/** /**
* a convince method for stopping the service and removing its que from the alarm manager * a convince method for stopping the service and removing its que from the alarm manager
* @param context * @param context
@@ -199,34 +60,72 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
@Override @Override
public void run(){ public void run(){
context.stopService(new Intent(context, SkyHookService.class)); context.stopService(new Intent(context, SkyHookService.class));
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context, SkyHookService.class), 0)); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context, SkyHookService.class), 0));
} }
}; };
} }
private SkyHook mSkyhook;
protected long mPeriod = -1;
private GeoPoint mLocation;
private int mStartID;
private int mRequiredAccuracy;
@Override private Intent mIntent;
public void onLocationChanged(GeoPoint point, int accuracy) {
this.mLocation = point; private int mAccuracy;
this.mAccuracy = accuracy;
/* /**
* fail safe * broadcasts location to anything listening for updates
* if the accuracy is greater than the minimum required accuracy *
* then continue * @author ricky barrette
* else stop to report location */
*/ private void braodcastLocation() {
if(accuracy < (this.mRequiredAccuracy > -1 ? this.mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION) if (mLocation != null) {
this.stopSelf(this.mStartID); final Intent locationUpdate = new Intent();
if(mIntent.getAction() != null)
locationUpdate.setAction(mIntent.getAction());
else
locationUpdate.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE);
locationUpdate.putExtra(LocationManager.KEY_LOCATION_CHANGED, convertLocation());
sendBroadcast(locationUpdate);
}
}
/**
* converts skyhook's location object into android's location object
* @return converted location
* @author ricky barrette
*/
public Location convertLocation(){
final Location location = new Location("location");
location.setLatitude(mLocation.getLatitudeE6() /1e6);
location.setLongitude(mLocation.getLongitudeE6() /1e6);
location.setAccuracy(mAccuracy);
return location;
} }
@Override @Override
public void done() { public void done() {
// unused // unused
} }
/*
* I believe that this method is no longer needed as we are not supporting pre 2.1
*/
// /**
// * To keep backwards compatibility we override onStart which is the equivalent of onStartCommand in pre android 2.x
// * @author ricky barrette
// */
// @Override
// public void onStart(Intent intent, int startId) {
// Log.i(SkyHook.TAG, "onStart.Service started with start id of: " + startId);
// parseIntent(intent);
// this.mSkyhook.getUpdates();
// }
@Override @Override
public WPSContinuation handleError(WPSReturnCode arg0) { public WPSContinuation handleError(final WPSReturnCode arg0) {
// unused // unused
return null; return null;
} }
@@ -234,12 +133,113 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
@Override @Override
public void handleSuccess() { public void handleSuccess() {
// unused // unused
}
/**
* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
* @param arg0
* @return
* @author Ricky Barrette barrette
*/
@Override
public IBinder onBind(final Intent arg0) {
return null;
} }
@Override @Override
public void onFirstFix(boolean isFistFix) { public void onCreate(){
super.onCreate();
mSkyhook = new SkyHook(this);
mSkyhook.setLocationListener(this);
/*
* fail safe
* this will stop the service after the maximum running time, if location has not been reported
*/
new Handler().postDelayed(new Runnable(){
@Override
public void run(){
stopSelfResult(mStartID);
}
}, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME);
}
/**
* aborts location services
* (non-Javadoc)
* @see android.app.Service#onDestroy()
* @author Ricky Barrette
*/
@Override
public void onDestroy(){
mSkyhook.removeUpdates();
braodcastLocation();
//ask android to restart service if mPeriod is set
if(mPeriod > -1)
registerWakeUp();
super.onDestroy();
}
@Override
public void onFirstFix(final boolean isFistFix) {
// unused // unused
}
@Override
public void onLocationChanged(final GeoPoint point, final int accuracy) {
mLocation = point;
mAccuracy = accuracy;
/*
* fail safe
* if the accuracy is greater than the minimum required accuracy
* then continue
* else stop to report location
*/
if(accuracy < (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION)
this.stopSelf(mStartID);
}
/**
* This method is called when startService is called. only used in 2.x android.
* @author ricky barrette
*/
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
Log.i(SkyHook.TAG , "onStartCommand.Service started with start id of: " + startId);
mStartID = startId;
parseIntent(intent);
mSkyhook.getUpdates();
return START_STICKY;
}
/**
* Parses the incoming intent for the service options
*
* @author ricky barrette
*/
private void parseIntent(final Intent intent){
mIntent = intent;
if(intent != null){
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES))
mPeriod = intent.getLongExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, LocationLibraryConstants.FAIL_SAFE_UPDATE_INVERVAL);
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY))
mRequiredAccuracy = intent.getIntExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY, LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY);
}
}
/**
* registers our Receiver the starts the service with the alarm manager
* @author ricky barrette
*/
private void registerWakeUp(){
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0));
} }
} }

View File

@@ -6,8 +6,6 @@
*/ */
package com.TwentyCodes.android.debug; package com.TwentyCodes.android.debug;
import com.TwentyCodes.android.location.BaseLocationReceiver;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.location.LocationManager; import android.location.LocationManager;
@@ -17,10 +15,10 @@ import android.location.LocationManager;
* @author ricky barrette * @author ricky barrette
*/ */
public final class LocationLibraryConstants { public final class LocationLibraryConstants {
static{ static{
SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO;
SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD;
} }
@@ -41,37 +39,37 @@ public final class LocationLibraryConstants {
* @author ricky barrette * @author ricky barrette
*/ */
public static final long MAX_LOCATION_SERVICE_RUN_TIME = 60000l; public static final long MAX_LOCATION_SERVICE_RUN_TIME = 60000l;
/** /**
* Forces single shot location services to return the first location * Forces single shot location services to return the first location
* @author ricky barrette * @author ricky barrette
*/ */
public static final boolean REPORT_FIRST_LOCATION = false; public static final boolean REPORT_FIRST_LOCATION = false;
/** /**
* Minimum Required accuracy to report * Minimum Required accuracy to report
* @author ricky barrette * @author ricky barrette
*/ */
public static final int MINIMUM_REQUIRED_ACCURACY = 100; public static final int MINIMUM_REQUIRED_ACCURACY = 100;
public static final boolean SUPPORTS_FROYO; public static final boolean SUPPORTS_FROYO;
public static final boolean SUPPORTS_GINGERBREAD; public static final boolean SUPPORTS_GINGERBREAD;
public static final String INTENT_ACTION_UPDATE = "TwentyCodes.intent.action.LocationUpdate"; public static final String INTENT_ACTION_UPDATE = "TwentyCodes.intent.action.LocationUpdate";
public static final String INTENT_EXTRA_LOCATION_CHANGED = LocationManager.KEY_LOCATION_CHANGED; public static final String INTENT_EXTRA_LOCATION_CHANGED = LocationManager.KEY_LOCATION_CHANGED;
/** /**
* Used to tell the service how frequently it needs to run. This is required if you want a multishot service * Used to tell the service how frequently it needs to run. This is required if you want a multishot service
*/ */
public static final String INTENT_EXTRA_PERIOD_BETWEEN_UPDATES = "period_beween_updates"; public static final String INTENT_EXTRA_PERIOD_BETWEEN_UPDATES = "period_beween_updates";
/** /**
* Used to tell the service how accurate of a location you want reported * Used to tell the service how accurate of a location you want reported
*/ */
public static final String INTENT_EXTRA_REQUIRED_ACCURACY = "required_accuracy"; public static final String INTENT_EXTRA_REQUIRED_ACCURACY = "required_accuracy";
/** /**
* used if the INTENT_EXTRA_PERIOD_BETWEEN_UPDATES is present, but contains no data * used if the INTENT_EXTRA_PERIOD_BETWEEN_UPDATES is present, but contains no data
*/ */

View File

@@ -15,16 +15,16 @@ public enum SkyHookRegistrationBehavior {
/** /**
* Used to force SkyHookRegistration.getUserName to behave normally * Used to force SkyHookRegistration.getUserName to behave normally
*/ */
NORMAL, NORMAL,
/** /**
* Used to force SkyHookRegistration.getUserName to return the testing user name * Used to force SkyHookRegistration.getUserName to return the testing user name
*/ */
USE_TESTING_USERNAME, USE_TESTING_USERNAME,
/** /**
* Used to force SkyHookRegistration.getUserName to return null * Used to force SkyHookRegistration.getUserName to return null
*/ */
RETURN_NULL; RETURN_NULL;
} }

View File

@@ -28,7 +28,7 @@ public abstract class BaseMapFragment extends Fragment {
private MapView mMapView; private MapView mMapView;
private boolean isGPSDialogEnabled; private boolean isGPSDialogEnabled;
private ProgressBar mProgress; private ProgressBar mProgress;
/** /**
* Creates a new MapFragment * Creates a new MapFragment
* @author ricky barrette * @author ricky barrette
@@ -36,11 +36,11 @@ public abstract class BaseMapFragment extends Fragment {
public BaseMapFragment() { public BaseMapFragment() {
super(); super();
} }
public void addOverlay(Overlay overlay){ public void addOverlay(final Overlay overlay){
mMapView.getOverlays().add(overlay); mMapView.getOverlays().add(overlay);
} }
/** /**
* changes the map mode * changes the map mode
* @author ricky barrette * @author ricky barrette
@@ -57,17 +57,17 @@ public abstract class BaseMapFragment extends Fragment {
isGPSDialogEnabled = false; isGPSDialogEnabled = false;
mProgress.setVisibility(View.GONE); mProgress.setVisibility(View.GONE);
} }
/** /**
* Enables the Acquiring GPS dialog if the location has not been acquired * Enables the Acquiring GPS dialog if the location has not been acquired
* *
* @author ricky barrette * @author ricky barrette
*/ */
public void enableGPSProgess(){ public void enableGPSProgess(){
isGPSDialogEnabled = true; isGPSDialogEnabled = true;
mProgress.setVisibility(View.VISIBLE); mProgress.setVisibility(View.VISIBLE);
} }
/** /**
* @return mapview * @return mapview
* @author ricky barrette * @author ricky barrette
@@ -75,120 +75,120 @@ public abstract class BaseMapFragment extends Fragment {
public MapView getMap(){ public MapView getMap(){
return mMapView; return mMapView;
} }
/** /**
* Forces the map to redraw * Forces the map to redraw
* @author ricky barrette * @author ricky barrette
*/ */
public void invalidate(){ public void invalidate(){
mMapView.invalidate(); mMapView.invalidate();
} }
/** /**
* @return true if the GPS progress is showing * @return true if the GPS progress is showing
* @author ricky barrette * @author ricky barrette
*/ */
public boolean isGPSProgessShowing(){ public boolean isGPSProgessShowing(){
return isGPSDialogEnabled; return isGPSDialogEnabled;
} }
/** /**
* @return true if the map is in satellite mode * @return true if the map is in satellite mode
* @author ricky barrette * @author ricky barrette
*/ */
public boolean isSatellite(){ public boolean isSatellite(){
return mMapView.isSatellite(); return mMapView.isSatellite();
} }
/** /**
* Called when the fragment view is first created * Called when the fragment view is first created
* (non-Javadoc) * (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/ */
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.base_map_fragment, container, false); final View view = inflater.inflate(R.layout.base_map_fragment, container, false);
mMapView = (MapView) view.findViewById(R.id.mapview); mMapView = (MapView) view.findViewById(R.id.mapview);
mMapView.setClickable(true); mMapView.setClickable(true);
mProgress = (ProgressBar) view.findViewById(R.id.mapProgressBar); mProgress = (ProgressBar) view.findViewById(R.id.mapProgressBar);
onMapViewCreate(mMapView); onMapViewCreate(mMapView);
return view; return view;
} }
/** /**
* Called when the mapview has been initialized. here you want to init and add your custom overlays * Called when the mapview has been initialized. here you want to init and add your custom overlays
* @param map * @param map
* @author ricky barrette * @author ricky barrette
*/ */
public abstract void onMapViewCreate(MapView map); public abstract void onMapViewCreate(MapView map);
/** /**
* Removes an overlay from the mapview * Removes an overlay from the mapview
* @param overlay * @param overlay
* @author ricky barrette * @author ricky barrette
*/ */
public void removeOverlay(Object overlay){ public void removeOverlay(final Object overlay){
mMapView.getOverlays().remove(overlay); mMapView.getOverlays().remove(overlay);
} }
/** /**
* Enables or disables the built in zoom controls * Enables or disables the built in zoom controls
* @param isShowing * @param isShowing
* @author ricky barrette * @author ricky barrette
*/ */
public void setBuiltInZoomControls(boolean isShowing){ public void setBuiltInZoomControls(final boolean isShowing){
mMapView.setBuiltInZoomControls(isShowing); mMapView.setBuiltInZoomControls(isShowing);
} }
/** /**
* Sets where or not the map view is interactive * Sets where or not the map view is interactive
* @param isClickable * @param isClickable
* @author ricky barrette * @author ricky barrette
*/ */
public void setClickable(boolean isClickable){ public void setClickable(final boolean isClickable){
mMapView.setClickable(isClickable); mMapView.setClickable(isClickable);
} }
/** /**
* Sets double tap zoom * Sets double tap zoom
* @param isDoubleTapZoonEnabled * @param isDoubleTapZoonEnabled
* @author ricky barrette * @author ricky barrette
*/ */
public void setDoubleTapZoonEnabled(boolean isDoubleTapZoonEnabled){ public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled){
mMapView.setDoubleTapZoonEnabled(isDoubleTapZoonEnabled); mMapView.setDoubleTapZoonEnabled(isDoubleTapZoonEnabled);
} }
/** /**
* Sets the center of the map to the provided point * Sets the center of the map to the provided point
* @param point * @param point
* @author ricky barrette * @author ricky barrette
*/ */
public boolean setMapCenter(GeoPoint point){ public boolean setMapCenter(final GeoPoint point){
if(point == null) if(point == null)
return false; return false;
mMapView.getController().setCenter(point); mMapView.getController().setCenter(point);
return true; return true;
} }
/** /**
* Sets the view of the map. true is sat, false is map * Sets the view of the map. true is sat, false is map
* @param isSat * @param isSat
* @author ricky barrette * @author ricky barrette
*/ */
public void setSatellite(boolean isSat){ public void setSatellite(final boolean isSat){
mMapView.setSatellite(isSat); mMapView.setSatellite(isSat);
} }
/** /**
* Sets the zoom level of the map * Sets the zoom level of the map
* @param zoom * @param zoom
* @author ricky barrette * @author ricky barrette
*/ */
public void setZoom(int zoom){ public void setZoom(final int zoom){
mMapView.getController().setZoom(zoom); mMapView.getController().setZoom(zoom);
} }
} }

View File

@@ -17,20 +17,29 @@ import com.TwentyCodes.android.location.R;
import com.TwentyCodes.android.overlays.DirectionsOverlay; import com.TwentyCodes.android.overlays.DirectionsOverlay;
/** /**
* this is a custom listview adaptor that wills a listview that has 2 textviews in each row. * this is a custom listview adaptor that wills a listview that has 2 textviews in each row.
* @author ricky barrette * @author ricky barrette
*/ */
public class DirectionsAdapter extends BaseAdapter { public class DirectionsAdapter extends BaseAdapter {
/**
* this class will hold the TextViews
* @author ricky barrette
*/
class ViewHolder {
TextView text;
TextView text2;
}
private final LayoutInflater mInflater; private final LayoutInflater mInflater;
private final DirectionsOverlay mDirections; private final DirectionsOverlay mDirections;
/** /**
* Creates a new DirectionsAdapter * Creates a new DirectionsAdapter
* @author ricky barrette * @author ricky barrette
*/ */
public DirectionsAdapter(Context context, DirectionsOverlay directions) { public DirectionsAdapter(final Context context, final DirectionsOverlay directions) {
mInflater = LayoutInflater.from(context); mInflater = LayoutInflater.from(context);
mDirections = directions; mDirections = directions;
} }
@@ -54,7 +63,7 @@ public class DirectionsAdapter extends BaseAdapter {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public Object getItem(int position) { public Object getItem(final int position) {
return position; return position;
} }
@@ -66,7 +75,7 @@ public class DirectionsAdapter extends BaseAdapter {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public long getItemId(int position) { public long getItemId(final int position) {
return position; return position;
} }
@@ -82,37 +91,27 @@ public class DirectionsAdapter extends BaseAdapter {
@Override @Override
public View getView(final int position, View convertView, final ViewGroup parent) { public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder; final ViewHolder holder;
if (convertView == null) { if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_row, null); convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder(); holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01); holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02); holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
/** convertView.setTag(holder);
* Display the copyrights on the bottom of the directions list } else
*/ holder = (ViewHolder) convertView.getTag();
if (position == mDirections.getDirections().size()){
holder.text.setText(mDirections.getCopyrights());
holder.text2.setText("");
} else {
holder.text.setText(Html.fromHtml(mDirections.getDirections().get(position)));
holder.text2.setText(mDirections.getDurations().get(position) +" : "+ mDirections.getDistances().get(position));
}
return convertView;
}
/** /**
* this class will hold the TextViews * Display the copyrights on the bottom of the directions list
* @author ricky barrette */
*/ if (position == mDirections.getDirections().size()){
class ViewHolder { holder.text.setText(mDirections.getCopyrights());
TextView text; holder.text2.setText("");
TextView text2; } else {
holder.text.setText(Html.fromHtml(mDirections.getDirections().get(position)));
holder.text2.setText(mDirections.getDurations().get(position) +" : "+ mDirections.getDistances().get(position));
}
return convertView;
} }
} }

View File

@@ -17,18 +17,18 @@ import com.TwentyCodes.android.overlays.DirectionsOverlay;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This fragment will be used to display directions to the user. * This fragment will be used to display directions to the user.
* When a specific direction is clicked, the corrispoding geopoint is returned via listener * When a specific direction is clicked, the corrispoding geopoint is returned via listener
* @author ricky barrette * @author ricky barrette
*/ */
public class DirectionsListFragment extends ListFragment { public class DirectionsListFragment extends ListFragment {
/** /**
* A simple interfrace for a directions list fragment * A simple interfrace for a directions list fragment
* @author ricky barrette * @author ricky barrette
*/ */
public interface OnDirectionSelectedListener { public interface OnDirectionSelectedListener {
/** /**
* Called when the user selects a direction from a directions list * Called when the user selects a direction from a directions list
* @param point * @param point
@@ -37,7 +37,7 @@ public class DirectionsListFragment extends ListFragment {
public void onDirectionSelected(GeoPoint point); public void onDirectionSelected(GeoPoint point);
} }
private OnDirectionSelectedListener mListener; private OnDirectionSelectedListener mListener;
private ArrayList<GeoPoint> mPoints; private ArrayList<GeoPoint> mPoints;
@@ -54,17 +54,17 @@ public class DirectionsListFragment extends ListFragment {
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public DirectionsListFragment(OnDirectionSelectedListener listener) { public DirectionsListFragment(final OnDirectionSelectedListener listener) {
this(); this();
mListener = listener; mListener = listener;
} }
/** /**
* Deletes all content in the listview * Deletes all content in the listview
* @author ricky barrette * @author ricky barrette
*/ */
public void clear() { public void clear() {
this.setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new ArrayList<String>())); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new ArrayList<String>()));
} }
/** /**
@@ -74,19 +74,19 @@ public class DirectionsListFragment extends ListFragment {
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/ */
@Override @Override
public void onListItemClick(ListView l, View w, int position, long id) { public void onListItemClick(final ListView l, final View w, final int position, final long id) {
if(position < mPoints.size()) if(position < mPoints.size())
if(mListener != null) if(mListener != null)
mListener.onDirectionSelected(mPoints.get(position)); mListener.onDirectionSelected(mPoints.get(position));
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.support.v4.app.Fragment#onStart() * @see android.support.v4.app.Fragment#onStart()
*/ */
@Override @Override
public void onStart() { public void onStart() {
this.setListShown(true); setListShown(true);
super.onStart(); super.onStart();
} }
@@ -97,7 +97,7 @@ public class DirectionsListFragment extends ListFragment {
*/ */
public void setDirections(final DirectionsOverlay directions) { public void setDirections(final DirectionsOverlay directions) {
mPoints = directions.getPoints(); mPoints = directions.getPoints();
this.setListAdapter(new DirectionsAdapter(getActivity(), directions)); setListAdapter(new DirectionsAdapter(getActivity(), directions));
} }
/** /**
@@ -105,7 +105,7 @@ public class DirectionsListFragment extends ListFragment {
* @param text * @param text
* @author ricky barrette * @author ricky barrette
*/ */
public void SetEmptyText(String text){ public void SetEmptyText(final String text){
this.setEmptyText(text); setEmptyText(text);
} }
} }

View File

@@ -31,16 +31,16 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
public SkyHoookUserOverlayMapFragment() { public SkyHoookUserOverlayMapFragment() {
super(); super();
} }
/** /**
* Tells the useroverlay to pan the map to follow the user * Tells the useroverlay to pan the map to follow the user
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(boolean followUser){ public void followUser(final boolean followUser){
mUserOverlay.followUser(followUser); mUserOverlay.followUser(followUser);
} }
/** /**
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
@@ -56,20 +56,20 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
public GeoPoint getUserLocation() { public GeoPoint getUserLocation() {
return mUserOverlay.getUserLocation(); return mUserOverlay.getUserLocation();
} }
/** /**
* Called when the compass is updated * Called when the compass is updated
* (non-Javadoc) * (non-Javadoc)
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
*/ */
@Override @Override
public void onCompassUpdate(float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if(mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
} }
@Override @Override
public void onFirstFix(boolean isFistFix) { public void onFirstFix(final boolean isFistFix) {
if(mGeoPointLocationListener != null) if(mGeoPointLocationListener != null)
mGeoPointLocationListener.onFirstFix(isFistFix); mGeoPointLocationListener.onFirstFix(isFistFix);
} }
@@ -79,7 +79,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(GeoPoint point, int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mGeoPointLocationListener != null) if(mGeoPointLocationListener != null)
mGeoPointLocationListener.onLocationChanged(point, accuracy); mGeoPointLocationListener.onLocationChanged(point, accuracy);
} }
@@ -89,16 +89,16 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView) * @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView)
*/ */
@Override @Override
public void onMapViewCreate(MapView map) { public void onMapViewCreate(final MapView map) {
mUserOverlay = new SkyHookUserOverlay(map, this.getActivity().getApplicationContext()); mUserOverlay = new SkyHookUserOverlay(map, getActivity().getApplicationContext());
mUserOverlay.registerListener(this); mUserOverlay.registerListener(this);
mUserOverlay.setCompassListener(this); mUserOverlay.setCompassListener(this);
mUserOverlay.enableCompass(); mUserOverlay.enableCompass();
mUserOverlay.followUser(true); mUserOverlay.followUser(true);
map.getOverlays().add(mUserOverlay); map.getOverlays().add(mUserOverlay);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onPause() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onPause()
@@ -109,7 +109,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
mUserOverlay.disableMyLocation(); mUserOverlay.disableMyLocation();
removeOverlay(mUserOverlay); removeOverlay(mUserOverlay);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume()
@@ -122,7 +122,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
addOverlay(mUserOverlay); addOverlay(mUserOverlay);
} }
} }
/** /**
* reorders the overlays to the UserOverlay always on top * reorders the overlays to the UserOverlay always on top
* @author ricky barrette * @author ricky barrette
@@ -131,7 +131,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
getMap().getOverlays().remove(mUserOverlay); getMap().getOverlays().remove(mUserOverlay);
getMap().getOverlays().add(mUserOverlay); getMap().getOverlays().add(mUserOverlay);
} }
/** /**
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
@@ -139,15 +139,15 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(int needleResId, int backgroundResId, int x, int y){ public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y){
mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y); mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y);
} }
/** /**
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(CompassListener listener){ public void setCompassListener(final CompassListener listener){
mCompassListener = listener; mCompassListener = listener;
} }
@@ -156,7 +156,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
mUserOverlay.setDestination(destination); mUserOverlay.setDestination(destination);
} }
@@ -164,7 +164,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setGeoPointLocationListener(GeoPointLocationListener listener){ public void setGeoPointLocationListener(final GeoPointLocationListener listener){
mGeoPointLocationListener = listener; mGeoPointLocationListener = listener;
} }
} }

View File

@@ -37,10 +37,10 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(boolean followUser){ public void followUser(final boolean followUser){
mUserOverlay.followUser(followUser); mUserOverlay.followUser(followUser);
} }
/** /**
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
@@ -56,20 +56,20 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
public GeoPoint getUserLocation() { public GeoPoint getUserLocation() {
return mUserOverlay.getUserLocation(); return mUserOverlay.getUserLocation();
} }
/** /**
* Called when the compass is updated * Called when the compass is updated
* (non-Javadoc) * (non-Javadoc)
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
*/ */
@Override @Override
public void onCompassUpdate(float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if(mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
} }
@Override @Override
public void onFirstFix(boolean isFistFix) { public void onFirstFix(final boolean isFistFix) {
if(mGeoPointLocationListener != null) if(mGeoPointLocationListener != null)
mGeoPointLocationListener.onFirstFix(isFistFix); mGeoPointLocationListener.onFirstFix(isFistFix);
} }
@@ -79,23 +79,23 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(GeoPoint point, int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mGeoPointLocationListener != null) if(mGeoPointLocationListener != null)
mGeoPointLocationListener.onLocationChanged(point, accuracy); mGeoPointLocationListener.onLocationChanged(point, accuracy);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView) * @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView)
*/ */
@Override @Override
public void onMapViewCreate(MapView map) { public void onMapViewCreate(final MapView map) {
mUserOverlay = new UserOverlay(map, this.getActivity().getApplicationContext()); mUserOverlay = new UserOverlay(map, getActivity().getApplicationContext());
mUserOverlay.registerListener(this); mUserOverlay.registerListener(this);
mUserOverlay.setCompassListener(this); mUserOverlay.setCompassListener(this);
mUserOverlay.enableCompass(); mUserOverlay.enableCompass();
mUserOverlay.followUser(true); mUserOverlay.followUser(true);
map.getOverlays().add(mUserOverlay); map.getOverlays().add(mUserOverlay);
} }
@@ -109,7 +109,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
mUserOverlay.disableMyLocation(); mUserOverlay.disableMyLocation();
removeOverlay(mUserOverlay); removeOverlay(mUserOverlay);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume()
@@ -122,7 +122,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
addOverlay(mUserOverlay); addOverlay(mUserOverlay);
} }
} }
/** /**
* reorders the overlays to the UserOverlay always on top * reorders the overlays to the UserOverlay always on top
* @author ricky barrette * @author ricky barrette
@@ -131,7 +131,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
getMap().getOverlays().remove(mUserOverlay); getMap().getOverlays().remove(mUserOverlay);
getMap().getOverlays().add(mUserOverlay); getMap().getOverlays().add(mUserOverlay);
} }
/** /**
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
@@ -139,7 +139,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(int needleResId, int backgroundResId, int x, int y){ public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y){
mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y); mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y);
} }
@@ -147,7 +147,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(CompassListener listener){ public void setCompassListener(final CompassListener listener){
mCompassListener = listener; mCompassListener = listener;
} }
@@ -156,7 +156,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
mUserOverlay.setDestination(destination); mUserOverlay.setDestination(destination);
} }
@@ -164,7 +164,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setGeoPointLocationListener(GeoPointLocationListener listener){ public void setGeoPointLocationListener(final GeoPointLocationListener listener){
mGeoPointLocationListener = listener; mGeoPointLocationListener = listener;
} }
} }

View File

@@ -22,22 +22,22 @@ import com.google.android.maps.GeoPoint;
* @author ricky barrette * @author ricky barrette
*/ */
public class AndroidGPS implements LocationListener { public class AndroidGPS implements LocationListener {
private static final String TAG = "AndroidGPS"; private static final String TAG = "AndroidGPS";
private final LocationManager mLocationManager; private final LocationManager mLocationManager;
private GeoPointLocationListener mListener; private GeoPointLocationListener mListener;
private LocationListener mLocationListener; private LocationListener mLocationListener;
private boolean isFirstFix; private boolean isFirstFix;
/** /**
* Creates a new SkyHookFallback * Creates a new SkyHookFallback
* @author ricky barrette * @author ricky barrette
*/ */
public AndroidGPS(Context context) { public AndroidGPS(final Context context) {
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isFirstFix = true; isFirstFix = true;
} }
/** /**
* Remove updates from androids location services * Remove updates from androids location services
* @author ricky barrette * @author ricky barrette
@@ -50,25 +50,11 @@ public class AndroidGPS implements LocationListener {
isFirstFix = true; isFirstFix = true;
} }
/**
* Attempts to enable periodic location updates
* @param listener
* @author ricky barrette
*/
public void enableLocationUpdates(LocationListener listener) {
if(Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()");
if(mLocationListener == null){
mLocationListener = listener;
requestUpdates();
}
}
/** /**
* request periodic location updates from androids location services * request periodic location updates from androids location services
* @author ricky barrette * @author ricky barrette
*/ */
public void enableLocationUpdates(GeoPointLocationListener listener) { public void enableLocationUpdates(final GeoPointLocationListener listener) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()"); Log.d(SkyHook.TAG, "enableLocationUpdates()");
if (mListener == null) { if (mListener == null) {
@@ -77,6 +63,20 @@ public class AndroidGPS implements LocationListener {
} }
} }
/**
* Attempts to enable periodic location updates
* @param listener
* @author ricky barrette
*/
public void enableLocationUpdates(final LocationListener listener) {
if(Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()");
if(mLocationListener == null){
mLocationListener = listener;
requestUpdates();
}
}
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.location.LocationListener#onLocationChanged(android.location.Location) * @see android.location.LocationListener#onLocationChanged(android.location.Location)
@@ -84,19 +84,18 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(Location location) { public void onLocationChanged(final Location location) {
if(mListener != null) { if(mListener != null) {
mListener.onLocationChanged(new GeoPoint( (int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), (int) location.getAccuracy()); mListener.onLocationChanged(new GeoPoint( (int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), (int) location.getAccuracy());
mListener.onFirstFix(isFirstFix); mListener.onFirstFix(isFirstFix);
} }
if(mLocationListener != null){ if(mLocationListener != null)
mLocationListener.onLocationChanged(location); mLocationListener.onLocationChanged(location);
}
isFirstFix = false; isFirstFix = false;
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.location.LocationListener#onProviderDisabled(java.lang.String) * @see android.location.LocationListener#onProviderDisabled(java.lang.String)
@@ -104,7 +103,7 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onProviderDisabled(String arg0) { public void onProviderDisabled(final String arg0) {
// UNUSED // UNUSED
} }
@@ -116,10 +115,10 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onProviderEnabled(String arg0) { public void onProviderEnabled(final String arg0) {
// UNUSED // UNUSED
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle) * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
@@ -129,7 +128,7 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) { public void onStatusChanged(final String arg0, final int arg1, final Bundle arg2) {
// UNUSED // UNUSED
} }
@@ -140,7 +139,7 @@ public class AndroidGPS implements LocationListener {
private void requestUpdates() { private void requestUpdates() {
try { try {
mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this); mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
} catch (IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
/* We do no handle this exception as it is caused if the android version is < 1.6. since the PASSIVE_PROVIDER call is not required /* We do no handle this exception as it is caused if the android version is < 1.6. since the PASSIVE_PROVIDER call is not required
* to function we can ignore it. * to function we can ignore it.

View File

@@ -16,25 +16,25 @@ import android.location.LocationManager;
* @author ricky barrette * @author ricky barrette
*/ */
public abstract class BaseLocationReceiver extends BroadcastReceiver { public abstract class BaseLocationReceiver extends BroadcastReceiver {
public Context mContext; public Context mContext;
/**
* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
final String key = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(key))
onLocationUpdate((Location)intent.getExtras().get(key));
}
/** /**
* called when a location update is received * called when a location update is received
* @param parcelableExtra * @param parcelableExtra
* @author ricky barrette * @author ricky barrette
*/ */
public abstract void onLocationUpdate(Location location); public abstract void onLocationUpdate(Location location);
/**
* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(final Context context, final Intent intent) {
mContext = context;
final String key = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(key))
onLocationUpdate((Location)intent.getExtras().get(key));
}
} }

View File

@@ -28,13 +28,13 @@ import com.TwentyCodes.android.debug.LocationLibraryConstants;
* @author ricky barrette * @author ricky barrette
*/ */
public class CompassSensor{ public class CompassSensor{
/** /**
* A simple listener interface to get updates from CompassSensor * A simple listener interface to get updates from CompassSensor
* @author ricky barrette * @author ricky barrette
*/ */
public interface CompassListener { public interface CompassListener {
/** /**
* Called when there is an update from the Compass Sensor * Called when there is an update from the Compass Sensor
* @param bearing * @param bearing
@@ -42,7 +42,7 @@ public class CompassSensor{
*/ */
public void onCompassUpdate(float bearing); public void onCompassUpdate(float bearing);
} }
public static final String TAG = "CompassSensor"; public static final String TAG = "CompassSensor";
private static final int BEARING = 0; private static final int BEARING = 0;
private final Display mDisplay; private final Display mDisplay;
@@ -55,7 +55,7 @@ public class CompassSensor{
static{ static{
mHandler = new Handler(){ mHandler = new Handler(){
@Override @Override
public void handleMessage(Message msg){ public void handleMessage(final Message msg){
if(mListener != null) if(mListener != null)
if(msg.what == BEARING) if(msg.what == BEARING)
mListener.onCompassUpdate((Float) msg.obj); mListener.onCompassUpdate((Float) msg.obj);
@@ -65,20 +65,25 @@ public class CompassSensor{
private final SensorEventListener mCallBack = new SensorEventListener() { private final SensorEventListener mCallBack = new SensorEventListener() {
private float[] mRotationMatrix = new float[16]; private final float[] mRotationMatrix = new float[16];
// private float[] mRemapedRotationMatrix = new float[16]; // private float[] mRemapedRotationMatrix = new float[16];
private float[] mI = new float[16]; private final float[] mI = new float[16];
private float[] mGravity = new float[3]; private float[] mGravity = new float[3];
private float[] mGeomag = new float[3]; private float[] mGeomag = new float[3];
private float[] mOrientVals = new float[3]; private final float[] mOrientVals = new float[3];
private double mAzimuth = 0; private double mAzimuth = 0;
// double mPitch = 0; // double mPitch = 0;
// double mRoll = 0; // double mRoll = 0;
// private float mInclination; // private float mInclination;
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
}
@Override
public void onSensorChanged(final SensorEvent sensorEvent) { public void onSensorChanged(final SensorEvent sensorEvent) {
if(Debug.DEBUG){ if(Debug.DEBUG)
switch (sensorEvent.accuracy){ switch (sensorEvent.accuracy){
case SensorManager.SENSOR_STATUS_UNRELIABLE: case SensorManager.SENSOR_STATUS_UNRELIABLE:
Log.v(TAG , "UNRELIABLE"); Log.v(TAG , "UNRELIABLE");
@@ -92,91 +97,86 @@ public class CompassSensor{
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH: case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
Log.v(TAG , "HIGH"); Log.v(TAG , "HIGH");
break; break;
}
// If the sensor data is unreliable return
if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
return;
// Gets the value of the sensor that has been changed
switch (sensorEvent.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
mGravity = sensorEvent.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
mGeomag = sensorEvent.values.clone();
break;
}
// If gravity and geomag have values then find rotation matrix
if (mGravity != null && mGeomag != null) {
// checks that the rotation matrix is found
final boolean success = SensorManager.getRotationMatrix(mRotationMatrix, mI, mGravity, mGeomag);
if (success) {
// switch (mDisplay.getOrientation()){
// case Surface.ROTATION_0:
// Log.v(TAG , "0");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_90:
// Log.v(TAG , "90");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_180:
// Log.v(TAG , "180");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_270:
// Log.v(TAG , "270");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix);
// break;
// }
/*
* remap cords due to Display.getRotation()
*/
SensorManager.getOrientation(mRotationMatrix, mOrientVals);
// mInclination = SensorManager.getInclination(mI);
mAzimuth = Math.toDegrees(mOrientVals[0]);
// mPitch = Math.toDegrees(mOrientVals[1]);
// mRoll = Math.toDegrees(mOrientVals[2]);
/*
* compensate for magentic delination
*/
mAzimuth += mDelination;
/*
* compensate for device orentation
*/
switch (mDisplay.getRotation()){
case Surface.ROTATION_0:
break;
case Surface.ROTATION_90:
mAzimuth = mAzimuth + 90;
break;
case Surface.ROTATION_180:
mAzimuth = mAzimuth +180;
break;
case Surface.ROTATION_270:
mAzimuth = mAzimuth - 90;
break;
}
} }
} }
// If the sensor data is unreliable return mHandler.sendMessage(mHandler.obtainMessage(BEARING, (float) mAzimuth));
if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
return;
// Gets the value of the sensor that has been changed
switch (sensorEvent.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
mGravity = sensorEvent.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
mGeomag = sensorEvent.values.clone();
break;
}
// If gravity and geomag have values then find rotation matrix
if (mGravity != null && mGeomag != null) {
// checks that the rotation matrix is found
boolean success = SensorManager.getRotationMatrix(mRotationMatrix, mI, mGravity, mGeomag);
if (success) {
// switch (mDisplay.getOrientation()){
// case Surface.ROTATION_0:
// Log.v(TAG , "0");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_90:
// Log.v(TAG , "90");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_180:
// Log.v(TAG , "180");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_270:
// Log.v(TAG , "270");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix);
// break;
// }
/*
* remap cords due to Display.getRotation()
*/
SensorManager.getOrientation(mRotationMatrix, mOrientVals);
// mInclination = SensorManager.getInclination(mI);
mAzimuth = Math.toDegrees(mOrientVals[0]);
// mPitch = Math.toDegrees(mOrientVals[1]);
// mRoll = Math.toDegrees(mOrientVals[2]);
/*
* compensate for magentic delination
*/
mAzimuth += mDelination;
/*
* compensate for device orentation
*/
switch (mDisplay.getOrientation()){
case Surface.ROTATION_0:
break;
case Surface.ROTATION_90:
mAzimuth = mAzimuth + 90;
break;
case Surface.ROTATION_180:
mAzimuth = mAzimuth +180;
break;
case Surface.ROTATION_270:
mAzimuth = mAzimuth - 90;
break;
}
}
}
mHandler.sendMessage(mHandler.obtainMessage(BEARING, (float) mAzimuth));
} }
};
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
/** /**
* Creates a new CompassSensor * Creates a new CompassSensor
* @author ricky barrette * @author ricky barrette
@@ -186,7 +186,7 @@ public class CompassSensor{
mDisplay = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); mDisplay = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
} }
/** /**
* Disables compass updates * Disables compass updates
* @author ricky barrette * @author ricky barrette
@@ -201,7 +201,7 @@ public class CompassSensor{
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(CompassListener listener){ public void enable(final CompassListener listener){
if(mListener == null) { if(mListener == null) {
mListener = listener; mListener = listener;
if(mSensorManager != null) if(mSensorManager != null)
@@ -216,21 +216,20 @@ public class CompassSensor{
}).start(); }).start();
} }
} }
/** /**
* Updates the Geomagnetic Field Declination based off of the provided location * Updates the Geomagnetic Field Declination based off of the provided location
* @param location last known (lat,lon,altitude), null will reset * @param location last known (lat,lon,altitude), null will reset
* @author ricky barrette * @author ricky barrette
*/ */
public void setDeclination(final Location location){ public void setDeclination(final Location location){
if (location != null) { if (location != null) {
final GeomagneticField geomagneticField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(), final GeomagneticField geomagneticField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(), Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(), Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis()); System.currentTimeMillis());
mDelination = geomagneticField.getDeclination(); mDelination = geomagneticField.getDeclination();
} else { } else
mDelination = 0; mDelination = 0;
}
} }
} }

View File

@@ -12,7 +12,14 @@ import com.google.android.maps.GeoPoint;
* @author ricky barrette * @author ricky barrette
*/ */
public interface GeoPointLocationListener { public interface GeoPointLocationListener {
/**
* Called when first fix is aquired
* @param isFirstFix
* @author ricky barrette
*/
public void onFirstFix(boolean isFirstFix);
/** /**
* Called when the location has changed * Called when the location has changed
* @param point * @param point
@@ -20,11 +27,4 @@ public interface GeoPointLocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
public void onLocationChanged(GeoPoint point, int accuracy); public void onLocationChanged(GeoPoint point, int accuracy);
/**
* Called when first fix is aquired
* @param isFirstFix
* @author ricky barrette
*/
public void onFirstFix(boolean isFirstFix);
} }

View File

@@ -35,72 +35,72 @@ import com.google.android.maps.MapView;
* @author Google Inc. * @author Google Inc.
*/ */
public class GeoUtils { public class GeoUtils {
public static final int EARTH_RADIUS_KM = 6371; public static final int EARTH_RADIUS_KM = 6371;
public static final double MILLION = 1000000; public static final double MILLION = 1000000;
/** /**
* Calculates the bearing from the user location to the destination location, or returns the bearing for north if there is no destination. * computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East
* This method is awesome for making a compass point toward the destination rather than North. * @param lat1 source lat
* @param user location * @param lon1 source lon
* @param dest location * @param lat2 destination lat
* @param bearing Degrees East from compass * @param lon2 destination lon
* @return Degrees East of dest location * @return the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East of true north
* @author ricky barrette * @author Google Inc.
*/ */
public static double bearing(final double lat1, final double lon1, final double lat2, final double lon2) {
final double lat1Rad = Math.toRadians(lat1);
final double lat2Rad = Math.toRadians(lat2);
final double deltaLonRad = Math.toRadians(lon2 - lon1);
final double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
final double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x));
}
/**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East of true north
* @param p1 source geopoint
* @param p2 destination geopoint
* @return the bearing of p2 in relationship from p1 in degrees East
* @author Google Inc.
*/
public static Double bearing(final GeoPoint p1, final GeoPoint p2) {
final double lat1 = p1.getLatitudeE6() / MILLION;
final double lon1 = p1.getLongitudeE6() / MILLION;
final double lat2 = p2.getLatitudeE6() / MILLION;
final double lon2 = p2.getLongitudeE6() / MILLION;
return bearing(lat1, lon1, lat2, lon2);
}
/**
* Calculates the bearing from the user location to the destination location, or returns the bearing for north if there is no destination.
* This method is awesome for making a compass point toward the destination rather than North.
* @param user location
* @param dest location
* @param bearing Degrees East from compass
* @return Degrees East of dest location
* @author ricky barrette
*/
public static float calculateBearing(final GeoPoint user, final GeoPoint dest, float bearing) { public static float calculateBearing(final GeoPoint user, final GeoPoint dest, float bearing) {
if( (user == null) || (dest == null) ) if( user == null || dest == null )
return bearing; return bearing;
float heading = bearing(user, dest).floatValue(); final float heading = bearing(user, dest).floatValue();
bearing = (360 - heading) + bearing; bearing = 360 - heading + bearing;
if (bearing > 360) if (bearing > 360)
return bearing - 360; return bearing - 360;
return bearing; return bearing;
} }
/** /**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East * Calculates a geopoint x meters away of the geopoint supplied. The new geopoint
* @param lat1 source lat
* @param lon1 source lon
* @param lat2 destination lat
* @param lon2 destination lon
* @return the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East of true north
* @author Google Inc.
*/
public static double bearing(final double lat1, final double lon1, final double lat2, final double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x));
}
/**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East of true north
* @param p1 source geopoint
* @param p2 destination geopoint
* @return the bearing of p2 in relationship from p1 in degrees East
* @author Google Inc.
*/
public static Double bearing(final GeoPoint p1, final GeoPoint p2) {
double lat1 = p1.getLatitudeE6() / MILLION;
double lon1 = p1.getLongitudeE6() / MILLION;
double lat2 = p2.getLatitudeE6() / MILLION;
double lon2 = p2.getLongitudeE6() / MILLION;
return bearing(lat1, lon1, lat2, lon2);
}
/**
* Calculates a geopoint x meters away of the geopoint supplied. The new geopoint
* shares the same latitude as geopoint point, this way they are on the same latitude arc. * shares the same latitude as geopoint point, this way they are on the same latitude arc.
* *
* @param point central geopoint * @param point central geopoint
* @param distance in meters from the geopoint * @param distance in meters from the geopoint
* @return geopoint that is x meters away from the geopoint supplied * @return geopoint that is x meters away from the geopoint supplied
* @author ricky barrette * @author ricky barrette
@@ -108,11 +108,11 @@ public class GeoUtils {
public static GeoPoint distanceFrom(final GeoPoint point, double distance){ public static GeoPoint distanceFrom(final GeoPoint point, double distance){
//convert meters into kilometers //convert meters into kilometers
distance = distance / 1000; distance = distance / 1000;
// convert lat and lon of geopoint to radians // convert lat and lon of geopoint to radians
double lat1Rad = Math.toRadians((point.getLatitudeE6() / 1e6)); final double lat1Rad = Math.toRadians(point.getLatitudeE6() / 1e6);
double lon1Rad = Math.toRadians((point.getLongitudeE6() / 1e6)); final double lon1Rad = Math.toRadians(point.getLongitudeE6() / 1e6);
/* /*
* kilometers = acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos(lon2Rad-lon1Rad)6371 * kilometers = acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos(lon2Rad-lon1Rad)6371
* *
@@ -123,36 +123,55 @@ public class GeoUtils {
* NOTE: sec(x) = 1/cos(x) * NOTE: sec(x) = 1/cos(x)
* *
* NOTE: that lat2Rad is = lat1Rad because we want to keep the new geopoint on the same lat arc * NOTE: that lat2Rad is = lat1Rad because we want to keep the new geopoint on the same lat arc
* therefore i saw no need to create a new variable for lat2Rad, * therefore i saw no need to create a new variable for lat2Rad,
* and simply inputed lat1Rad in place of lat2Rad in the equation * and simply inputed lat1Rad in place of lat2Rad in the equation
* *
* NOTE: this equation has be tested in the field against another gps device, and the distanceKm() from google * NOTE: this equation has be tested in the field against another gps device, and the distanceKm() from google
* and has been proven to be damn close * and has been proven to be damn close
*/ */
double lon2Rad = lon1Rad + Math.acos( Math.cos((distance/6371)) * (1 / Math.cos(lat1Rad)) final double lon2Rad = lon1Rad + Math.acos( Math.cos(distance/6371) * (1 / Math.cos(lat1Rad))
* (1 / Math.cos(lat1Rad)) - Math.tan(lat1Rad) * Math.tan(lat1Rad)); * (1 / Math.cos(lat1Rad)) - Math.tan(lat1Rad) * Math.tan(lat1Rad));
//return a geopoint that is x meters away from the geopoint supplied //return a geopoint that is x meters away from the geopoint supplied
return new GeoPoint(point.getLatitudeE6(), (int) (Math.toDegrees(lon2Rad) * 1e6)); return new GeoPoint(point.getLatitudeE6(), (int) (Math.toDegrees(lon2Rad) * 1e6));
} }
/** /**
* computes the distance between to lat1/lon1 and lat2/lon2 based on the curve of the earth * computes the distance between to lat1/lon1 and lat2/lon2 based on the curve of the earth
* @param lat1 source lat * @param lat1 source lat
* @param lon1 source lon * @param lon1 source lon
* @param lat2 destination lat * @param lat2 destination lat
* @param lon2 destination lon * @param lon2 destination lon
* @return the distance between to lat1/lon1 and lat2/lon2 * @return the distance between to lat1/lon1 and lat2/lon2
* @author Google Inc. * @author Google Inc.
*/ */
public static double distanceKm(final double lat1, final double lon1, final double lat2, final double lon2) { public static double distanceKm(final double lat1, final double lon1, final double lat2, final double lon2) {
double lat1Rad = Math.toRadians(lat1); final double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2); final double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1); final double deltaLonRad = Math.toRadians(lon2 - lon1);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM;
} }
/** /**
* computes the distance between to p1 and p2 based on the curve of the earth
* @param p1
* @param p2
* @return the distance between to p1 and p2
* @author Google Inc.
*/
public static double distanceKm(final GeoPoint p1, final GeoPoint p2) {
//if we are handed a null, return -1 so we don't break
if(p1 == null || p2 == null)
return -1;
final double lat1 = p1.getLatitudeE6() / MILLION;
final double lon1 = p1.getLongitudeE6() / MILLION;
final double lat2 = p2.getLatitudeE6() / MILLION;
final double lon2 = p2.getLongitudeE6() / MILLION;
return distanceKm(lat1, lon1, lat2, lon2);
}
/**
* Converts distance into a human readbale string * Converts distance into a human readbale string
* @param distance in kilometers * @param distance in kilometers
* @param returnMetric true if metric, false for US * @param returnMetric true if metric, false for US
@@ -160,8 +179,8 @@ public class GeoUtils {
* @author ricky barrette * @author ricky barrette
*/ */
public static String distanceToString(double distance, final boolean returnMetric) { public static String distanceToString(double distance, final boolean returnMetric) {
DecimalFormat threeDForm = new DecimalFormat("#.###"); final DecimalFormat threeDForm = new DecimalFormat("#.###");
DecimalFormat twoDForm = new DecimalFormat("#.##"); final DecimalFormat twoDForm = new DecimalFormat("#.##");
if (returnMetric) { if (returnMetric) {
if (distance < 1) { if (distance < 1) {
@@ -177,12 +196,12 @@ public class GeoUtils {
} }
return twoDForm.format(distance) + " mi"; return twoDForm.format(distance) + " mi";
} }
/** /**
* a convince method for testing if 2 circles on the the surface of the earth intersect. * a convince method for testing if 2 circles on the the surface of the earth intersect.
* we will use this method to test if the users accuracy circle intersects a marked locaton's radius * we will use this method to test if the users accuracy circle intersects a marked locaton's radius
* if ( (accuracyCircleRadius + locationRadius) - fudgeFactor) > acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos(lon2Rad-lon1Rad)6371 * if ( (accuracyCircleRadius + locationRadius) - fudgeFactor) > acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos(lon2Rad-lon1Rad)6371
* @param userPoint * @param userPoint
* @param accuracyRadius in KM * @param accuracyRadius in KM
* @param locationPoint * @param locationPoint
* @param locationRadius in KM * @param locationRadius in KM
@@ -191,31 +210,12 @@ public class GeoUtils {
* @author ricky barrette * @author ricky barrette
*/ */
public static boolean isIntersecting(final GeoPoint userPoint, final float accuracyRadius, final GeoPoint locationPoint, final float locationRadius, final float fudgeFactor){ public static boolean isIntersecting(final GeoPoint userPoint, final float accuracyRadius, final GeoPoint locationPoint, final float locationRadius, final float fudgeFactor){
if(((accuracyRadius + locationRadius) - fudgeFactor) > distanceKm(locationPoint, userPoint)) if(accuracyRadius + locationRadius - fudgeFactor > distanceKm(locationPoint, userPoint))
return true; return true;
return false; return false;
} }
/** /**
* computes the distance between to p1 and p2 based on the curve of the earth
* @param p1
* @param p2
* @return the distance between to p1 and p2
* @author Google Inc.
*/
public static double distanceKm(final GeoPoint p1, final GeoPoint p2) {
//if we are handed a null, return -1 so we don't break
if(p1 == null || p2 == null)
return -1;
double lat1 = p1.getLatitudeE6() / MILLION;
double lon1 = p1.getLongitudeE6() / MILLION;
double lat2 = p2.getLatitudeE6() / MILLION;
double lon2 = p2.getLongitudeE6() / MILLION;
return distanceKm(lat1, lon1, lat2, lon2);
}
/**
* determines when the specified point is off the map * determines when the specified point is off the map
* @param point * @param point
* @return true is the point is off the map * @return true is the point is off the map
@@ -226,58 +226,57 @@ public class GeoUtils {
return false; return false;
if (point == null) if (point == null)
return false; return false;
GeoPoint center = map.getMapCenter(); final GeoPoint center = map.getMapCenter();
double distance = GeoUtils.distanceKm(center, point); final double distance = GeoUtils.distanceKm(center, point);
double distanceLat = GeoUtils.distanceKm(center, new GeoPoint((center.getLatitudeE6() + (int) (map.getLatitudeSpan() / 2)), center.getLongitudeE6())); final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + map.getLatitudeSpan() / 2, center.getLongitudeE6()));
double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), (center.getLongitudeE6() + (int) (map.getLongitudeSpan() / 2)))); final double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), center.getLongitudeE6() + map.getLongitudeSpan() / 2));
if (distance > distanceLat || distance > distanceLon){ if (distance > distanceLat || distance > distanceLon)
return true; return true;
}
return false; return false;
} }
/** /**
* computes a geopoint the is the central geopoint between p1 and p1 * computes a geopoint the is the central geopoint between p1 and p1
* @param p1 first geopoint * @param p1 first geopoint
* @param p2 second geopoint * @param p2 second geopoint
* @return a MidPoint object * @return a MidPoint object
* @author ricky barrette * @author ricky barrette
*/ */
public static MidPoint midPoint(final GeoPoint p1, final GeoPoint p2) { public static MidPoint midPoint(final GeoPoint p1, final GeoPoint p2) {
int minLatitude = (int)(+81 * 1E6); int minLatitude = (int)(+81 * 1E6);
int maxLatitude = (int)(-81 * 1E6); int maxLatitude = (int)(-81 * 1E6);
int minLongitude = (int)(+181 * 1E6); int minLongitude = (int)(+181 * 1E6);
int maxLongitude = (int)(-181 * 1E6); int maxLongitude = (int)(-181 * 1E6);
List<Point> mPoints = new ArrayList<Point>(); final List<Point> mPoints = new ArrayList<Point>();
int latitude = p1.getLatitudeE6(); int latitude = p1.getLatitudeE6();
int longitude = p1.getLongitudeE6(); int longitude = p1.getLongitudeE6();
if (latitude != 0 && longitude !=0) { if (latitude != 0 && longitude !=0) {
minLatitude = (minLatitude > latitude) ? latitude : minLatitude; minLatitude = minLatitude > latitude ? latitude : minLatitude;
maxLatitude = (maxLatitude < latitude) ? latitude : maxLatitude; maxLatitude = maxLatitude < latitude ? latitude : maxLatitude;
minLongitude = (minLongitude > longitude) ? longitude : minLongitude; minLongitude = minLongitude > longitude ? longitude : minLongitude;
maxLongitude = (maxLongitude < longitude) ? longitude : maxLongitude; maxLongitude = maxLongitude < longitude ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude)); mPoints.add(new Point(latitude, longitude));
} }
latitude = p2.getLatitudeE6(); latitude = p2.getLatitudeE6();
longitude = p2.getLongitudeE6(); longitude = p2.getLongitudeE6();
if (latitude != 0 && longitude !=0) { if (latitude != 0 && longitude !=0) {
minLatitude = (minLatitude > latitude) ? latitude : minLatitude; minLatitude = minLatitude > latitude ? latitude : minLatitude;
maxLatitude = (maxLatitude < latitude) ? latitude : maxLatitude; maxLatitude = maxLatitude < latitude ? latitude : maxLatitude;
minLongitude = (minLongitude > longitude) ? longitude : minLongitude; minLongitude = minLongitude > longitude ? longitude : minLongitude;
maxLongitude = (maxLongitude < longitude) ? longitude : maxLongitude; maxLongitude = maxLongitude < longitude ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude)); mPoints.add(new Point(latitude, longitude));
} }
return new MidPoint(new GeoPoint((maxLatitude + minLatitude)/2, (maxLongitude + minLongitude)/2 ), minLatitude, minLongitude, maxLatitude, maxLongitude); return new MidPoint(new GeoPoint((maxLatitude + minLatitude)/2, (maxLongitude + minLongitude)/2 ), minLatitude, minLongitude, maxLatitude, maxLongitude);
} }
/** /**
* converts radians to bearing * converts radians to bearing
* @param rad * @param rad
* @return bearing * @return bearing
* @author Google Inc. * @author Google Inc.
*/ */
public static double radToBearing(final double rad) { public static double radToBearing(final double rad) {
return (Math.toDegrees(rad) + 360) % 360; return (Math.toDegrees(rad) + 360) % 360;
} }
} }

View File

@@ -37,37 +37,53 @@ import com.TwentyCodes.android.debug.LocationLibraryConstants;
* @author ricky barrette * @author ricky barrette
*/ */
public class LocationService extends Service implements LocationListener { public class LocationService extends Service implements LocationListener {
public static final String TAG = "LocationService"; public static final String TAG = "LocationService";
private static final int REQUEST_CODE = 7893749; private static final int REQUEST_CODE = 7893749;
/**
*a convince method for getting an intent to start the service
* @param context
* @return a intent that will start the service
* @author ricky barrette
*/
public static Intent getStartServiceIntent(final Context context){
return new Intent(context, LocationService.class);
}
/**
* a convince method for stopping the service and removing it's alarm
* @param context
* @return a runnable that will stop the service
* @author ricky barrette
*/
public static Runnable stopService(final Context context){
return new Runnable(){
@Override
public void run(){
context.stopService(new Intent(context, LocationService.class));
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context, LocationService.class), 0));
}
};
}
private WakeLock mWakeLock; private WakeLock mWakeLock;
private long mPeriod = -1; private long mPeriod = -1;
private Location mLocation; private Location mLocation;
private int mStartId; private int mStartId;
private AndroidGPS mLocationManager; private AndroidGPS mLocationManager;
private int mRequiredAccuracy; private int mRequiredAccuracy;
private Intent mIntent; private Intent mIntent;
/* /*
* this runnable will be qued when the service is created. this will be used as a fail safe * this runnable will be qued when the service is created. this will be used as a fail safe
*/ */
private Runnable failSafe = new Runnable() { private final Runnable failSafe = new Runnable() {
@Override @Override
public void run(){ public void run(){
stopSelf(mStartId); stopSelf(mStartId);
} }
}; };
/**
* registers this service to be waken up by android's alarm manager
* @author ricky barrette
*/
private void registerwakeUp(){
Log.d(TAG, "registerwakeUp()");
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + this.mPeriod, PendingIntent.getService(this, REQUEST_CODE, this.mIntent, 0));
}
/** /**
* broadcasts location to anything listening for updates, * broadcasts location to anything listening for updates,
* since this is the last function of the service, we call finish()u * since this is the last function of the service, we call finish()u
@@ -76,7 +92,7 @@ public class LocationService extends Service implements LocationListener {
private void broadcastLocation() { private void broadcastLocation() {
Log.d(TAG, "broadcastLocation()"); Log.d(TAG, "broadcastLocation()");
if (mLocation != null) { if (mLocation != null) {
Intent locationUpdate = new Intent(); final Intent locationUpdate = new Intent();
if(mIntent.getAction() != null) if(mIntent.getAction() != null)
locationUpdate.setAction(mIntent.getAction()); locationUpdate.setAction(mIntent.getAction());
else else
@@ -87,6 +103,19 @@ public class LocationService extends Service implements LocationListener {
} }
} }
/**
* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
* @param arg0
* @return
* @author ricky barrette
*/
@Override
public IBinder onBind(final Intent arg0) {
// UNUSED
return null;
}
/** /**
* called when the service is created. this will initialize the location manager, and acquire a wakelock * called when the service is created. this will initialize the location manager, and acquire a wakelock
* (non-Javadoc) * (non-Javadoc)
@@ -96,19 +125,19 @@ public class LocationService extends Service implements LocationListener {
@Override @Override
public void onCreate(){ public void onCreate(){
mLocationManager = new AndroidGPS(this); mLocationManager = new AndroidGPS(this);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire(); mWakeLock.acquire();
/* /*
* que the fail safe runnable to kill the report location and kill it self after the MAX_RUN_TIME has been meet * que the fail safe runnable to kill the report location and kill it self after the MAX_RUN_TIME has been meet
*/ */
new Handler().postDelayed(failSafe, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME); new Handler().postDelayed(failSafe, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME);
super.onCreate(); super.onCreate();
} }
/** /**
* called when the service is destroyed. * called when the service is destroyed.
* this will remove any wakelock or location service running, and register to be waken back up * this will remove any wakelock or location service running, and register to be waken back up
* (non-Javadoc) * (non-Javadoc)
* @see android.app.Service#onDestroy() * @see android.app.Service#onDestroy()
@@ -123,119 +152,89 @@ public class LocationService extends Service implements LocationListener {
if(mPeriod > -1) if(mPeriod > -1)
registerwakeUp(); registerwakeUp();
} }
@Override
public void onLocationChanged(final Location location) {
if(Debug.DEBUG)
Log.d(TAG, "got location +- "+ location.getAccuracy() +"m");
mLocation = location;
if(location.getAccuracy() <= (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION)
stopSelf(mStartId);
}
@Override
public void onProviderDisabled(final String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(final String provider) {
// TODO Auto-generated method stub
}
/** /**
* To keep backwards compatibility we override onStart which is the equivalent of onStartCommand in pre android 2.x * To keep backwards compatibility we override onStart which is the equivalent of onStartCommand in pre android 2.x
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onStart(Intent intent, int startId) { public void onStart(final Intent intent, final int startId) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.i(TAG, "onStart.Service started with start id of: " + startId); Log.i(TAG, "onStart.Service started with start id of: " + startId);
mStartId = startId; mStartId = startId;
parseIntent(intent); parseIntent(intent);
mLocationManager.enableLocationUpdates(this); mLocationManager.enableLocationUpdates(this);
} }
/** /**
* This method is called when startService is called. only used in 2.x android. * This method is called when startService is called. only used in 2.x android.
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(final Intent intent, final int flags, final int startId) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.i(TAG , "onStartCommand.Service started with start id of: " + startId); Log.i(TAG , "onStartCommand.Service started with start id of: " + startId);
mStartId = startId; mStartId = startId;
parseIntent(intent); parseIntent(intent);
mLocationManager.enableLocationUpdates(this); mLocationManager.enableLocationUpdates(this);
return START_STICKY; return START_STICKY;
} }
@Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
// TODO Auto-generated method stub
}
/** /**
* Parses the incoming intent for the service options * Parses the incoming intent for the service options
* *
* @author ricky barrette * @author ricky barrette
*/ */
private void parseIntent(Intent intent){ private void parseIntent(final Intent intent){
this.mIntent = intent; mIntent = intent;
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES)) if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES))
mPeriod = intent.getLongExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, LocationLibraryConstants.FAIL_SAFE_UPDATE_INVERVAL); mPeriod = intent.getLongExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, LocationLibraryConstants.FAIL_SAFE_UPDATE_INVERVAL);
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY)) if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY))
mRequiredAccuracy = intent.getIntExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY, LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY); mRequiredAccuracy = intent.getIntExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY, LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY);
} }
/**
* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
* @param arg0
* @return
* @author ricky barrette
*/
@Override
public IBinder onBind(Intent arg0) {
// UNUSED
return null;
}
/** /**
*a convince method for getting an intent to start the service * registers this service to be waken up by android's alarm manager
* @param context
* @return a intent that will start the service
* @author ricky barrette * @author ricky barrette
*/ */
public static Intent getStartServiceIntent(final Context context){ private void registerwakeUp(){
return new Intent(context, LocationService.class); Log.d(TAG, "registerwakeUp()");
} final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0));
/**
* a convince method for stopping the service and removing it's alarm
* @param context
* @return a runnable that will stop the service
* @author ricky barrette
*/
public static Runnable stopService(final Context context){
return new Runnable(){
@Override
public void run(){
context.stopService(new Intent(context, LocationService.class));
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context, LocationService.class), 0));
}
};
}
@Override
public void onLocationChanged(Location location) {
if(Debug.DEBUG)
Log.d(TAG, "got location +- "+ location.getAccuracy() +"m");
mLocation = location;
if(location.getAccuracy() <= (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION){
stopSelf(mStartId);
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
} }
} }

View File

@@ -5,14 +5,14 @@
*/ */
package com.TwentyCodes.android.location; package com.TwentyCodes.android.location;
import com.TwentyCodes.android.debug.Debug;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.MotionEvent; import android.view.MotionEvent;
import com.TwentyCodes.android.debug.Debug;
/** /**
* We use this MapView Because it has double tap zoom capability and exception handling * We use this MapView Because it has double tap zoom capability and exception handling
* @author ricky barrette * @author ricky barrette
@@ -23,21 +23,12 @@ public class MapView extends com.google.android.maps.MapView {
private long mLastTouchTime; private long mLastTouchTime;
private boolean mDoubleTapZoonEnabled = true; private boolean mDoubleTapZoonEnabled = true;
/**
* @param context
* @param apiKey
* @author ricky barrette
*/
public MapView(Context context, String apiKey) {
super(context, apiKey);
}
/** /**
* @param context * @param context
* @param attrs * @param attrs
* @author ricky barrette * @author ricky barrette
*/ */
public MapView(Context context, AttributeSet attrs) { public MapView(final Context context, final AttributeSet attrs) {
super(context, attrs); super(context, attrs);
} }
@@ -47,57 +38,38 @@ public class MapView extends com.google.android.maps.MapView {
* @param defStyle * @param defStyle
* @author ricky barrette * @author ricky barrette
*/ */
public MapView(Context context, AttributeSet attrs, int defStyle) { public MapView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
} }
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) { /**
* @param context
long thisTime = System.currentTimeMillis(); * @param apiKey
if (this.mDoubleTapZoonEnabled && thisTime - mLastTouchTime < 250) { * @author ricky barrette
// Double tap */
this.getController().zoomInFixing((int) ev.getX(), (int) ev.getY()); public MapView(final Context context, final String apiKey) {
mLastTouchTime = -1; super(context, apiKey);
} else {
// Too slow
mLastTouchTime = thisTime;
}
}
return super.onInterceptTouchEvent(ev);
} }
/** /**
* We will override the draw method to help prevent issues * We will override the draw method to help prevent issues
* (non-Javadoc) * (non-Javadoc)
* @see android.view.View#draw(android.graphics.Canvas) * @see android.view.View#draw(android.graphics.Canvas)
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(Canvas canvas) { public void draw(final Canvas canvas) {
try { try {
if(this.getZoomLevel() >= 21) { if(getZoomLevel() >= 21)
this.getController().setZoom(20); getController().setZoom(20);
} super.draw(canvas);
super.draw(canvas); }
} catch(final Exception ex) {
catch(Exception ex) { // getController().setCenter(this.getMapCenter());
// getController().setCenter(this.getMapCenter()); // getController().setZoom(this.getZoomLevel() - 2);
// getController().setZoom(this.getZoomLevel() - 2); if(Debug.DEBUG)
if(Debug.DEBUG) Log.d(TAG, "Internal error in MapView:" + Log.getStackTraceString(ex));
Log.d(TAG, "Internal error in MapView:" + Log.getStackTraceString(ex)); }
}
}
/**
* @param isDoubleTapZoonEnabled the isDoubleTapZoonEnabled to set
* @author ricky barrette
*/
public void setDoubleTapZoonEnabled(boolean isDoubleTapZoonEnabled) {
this.mDoubleTapZoonEnabled = isDoubleTapZoonEnabled;
} }
/** /**
@@ -107,4 +79,30 @@ public class MapView extends com.google.android.maps.MapView {
public boolean getDoubleTapZoonEnabled() { public boolean getDoubleTapZoonEnabled() {
return mDoubleTapZoonEnabled; return mDoubleTapZoonEnabled;
} }
@Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
final long thisTime = System.currentTimeMillis();
if (mDoubleTapZoonEnabled && thisTime - mLastTouchTime < 250) {
// Double tap
getController().zoomInFixing((int) ev.getX(), (int) ev.getY());
mLastTouchTime = -1;
} else
// Too slow
mLastTouchTime = thisTime;
}
return super.onInterceptTouchEvent(ev);
}
/**
* @param isDoubleTapZoonEnabled the isDoubleTapZoonEnabled to set
* @author ricky barrette
*/
public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled) {
mDoubleTapZoonEnabled = isDoubleTapZoonEnabled;
}
} }

View File

@@ -8,11 +8,11 @@ package com.TwentyCodes.android.location;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This MidPoint object will hold the information form the calculations performed by GeoUtils.midPoint(). * This MidPoint object will hold the information form the calculations performed by GeoUtils.midPoint().
* @author ricky barrette * @author ricky barrette
*/ */
public class MidPoint { public class MidPoint {
private final int mMinLatitude; private final int mMinLatitude;
private final int mMaxLatitude; private final int mMaxLatitude;
private final int mMinLongitude; private final int mMinLongitude;
@@ -23,23 +23,14 @@ public class MidPoint {
* Creates a new MidPoint * Creates a new MidPoint
* @author ricky barrette * @author ricky barrette
*/ */
public MidPoint(GeoPoint midPoint, int minLatitude, int minLongitude, int maxLatitude, int maxLongitude) { public MidPoint(final GeoPoint midPoint, final int minLatitude, final int minLongitude, final int maxLatitude, final int maxLongitude) {
mMinLatitude = minLatitude; mMinLatitude = minLatitude;
mMaxLatitude = maxLatitude; mMaxLatitude = maxLatitude;
mMinLongitude = minLongitude; mMinLongitude = minLongitude;
mMaxLongitude = maxLongitude; mMaxLongitude = maxLongitude;
mMidPoint = midPoint; mMidPoint = midPoint;
} }
/**
* zooms the provided map view to the span of this mid point
* @param mMapView
* @author ricky barrette
*/
public void zoomToSpan(com.google.android.maps.MapView mMapView){
mMapView.getController().zoomToSpan((mMaxLatitude - mMinLatitude), (mMaxLongitude - mMinLongitude));
}
/** /**
* returns the calculated midpoint * returns the calculated midpoint
* @return * @return
@@ -48,4 +39,13 @@ public class MidPoint {
public GeoPoint getMidPoint(){ public GeoPoint getMidPoint(){
return mMidPoint; return mMidPoint;
} }
/**
* zooms the provided map view to the span of this mid point
* @param mMapView
* @author ricky barrette
*/
public void zoomToSpan(final com.google.android.maps.MapView mMapView){
mMapView.getController().zoomToSpan(mMaxLatitude - mMinLatitude, mMaxLongitude - mMinLongitude);
}
} }

View File

@@ -27,9 +27,9 @@ public class PassiveLocationListener {
*/ */
public static final void requestPassiveLocationUpdates(final Context context, final Intent receiverIntent){ public static final void requestPassiveLocationUpdates(final Context context, final Intent receiverIntent){
if (LocationLibraryConstants.SUPPORTS_FROYO) { if (LocationLibraryConstants.SUPPORTS_FROYO) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final PendingIntent locationListenerPassivePendingIntent = PendingIntent.getBroadcast(context, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT); final PendingIntent locationListenerPassivePendingIntent = PendingIntent.getBroadcast(context, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListenerPassivePendingIntent); locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListenerPassivePendingIntent);
} }
} }
} }

View File

@@ -36,114 +36,114 @@ public class ReverseGeocoder {
private static final String TAG = "ReverseGeocoder"; private static final String TAG = "ReverseGeocoder";
/** /**
* Performs a google maps search for the address * Performs a google maps search for the address
* @param location * @param address to search
* @return JSON Array on google place marks nearby * @return JSON Array of google place marks
* @throws IOException
* @throws JSONException
* @author ricky barrette * @author ricky barrette
* @throws IOException
* @throws JSONException
*/ */
public static JSONArray getFromLocation(final Location location) throws IOException, JSONException { public static JSONArray addressSearch(final String address) throws IOException, JSONException {
String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false"; String urlStr = "http://maps.google.com/maps/geo?q=" + address + "&output=json&sensor=false";
StringBuffer response = new StringBuffer(); urlStr = urlStr.replace(' ', '+');
HttpClient client = new DefaultHttpClient(); final StringBuffer response = new StringBuffer();
final HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, response.toString()); Log.d(TAG, response.toString());
return new JSONObject(response.toString()).getJSONArray("Placemark"); return new JSONObject(response.toString()).getJSONArray("Placemark");
} }
/** /**
* Performs a google maps search for the closest address to the location * Performs a google maps search for the closest address to the location
* @param lat * @param lat
* @param lon * @param lon
* @return string address, or lat, lon if search fails * @return string address, or lat, lon if search fails
* @author ricky barrette * @author ricky barrette
*/ */
public static String getAddressFromLocation(final Location location) { public static String getAddressFromLocation(final Location location) {
String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false"; final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false";
StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
HttpClient client = new DefaultHttpClient(); final HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
try { try {
HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, response.toString()); Log.d(TAG, response.toString());
JSONArray responseArray = null; JSONArray responseArray = null;
try { try {
responseArray = new JSONObject(response.toString()).getJSONArray("Placemark"); responseArray = new JSONObject(response.toString()).getJSONArray("Placemark");
} catch (JSONException e) { } catch (final JSONException e) {
return location.getLatitude() +", "+ location.getLongitude() +" ± "+ location.getAccuracy()+"m"; return location.getLatitude() +", "+ location.getLongitude() +" +/- "+ location.getAccuracy()+"m";
} }
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG,responseArray.length() + " result(s)"); Log.d(TAG,responseArray.length() + " result(s)");
try { try {
JSONObject jsl = responseArray.getJSONObject(0); final JSONObject jsl = responseArray.getJSONObject(0);
return jsl.getString("address"); return jsl.getString("address");
} catch (JSONException e) { } catch (final JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
return location.getLatitude() +", "+ location.getLongitude() +" ± "+ location.getAccuracy()+"m"; return location.getLatitude() +", "+ location.getLongitude() +" +/- "+ location.getAccuracy()+"m";
} }
/** /**
* Performs a google maps search for the address * Performs a google maps search for the address
* @param address to search * @param location
* @return JSON Array of google place marks * @return JSON Array on google place marks nearby
* @throws IOException * @author ricky barrette
* @throws JSONException * @throws IOException
* @author ricky barrette * @throws JSONException
*/ */
public static JSONArray addressSearch(final String address) throws IOException, JSONException { public static JSONArray getFromLocation(final Location location) throws IOException, JSONException {
String urlStr = "http://maps.google.com/maps/geo?q=" + address + "&output=json&sensor=false"; final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false";
urlStr = urlStr.replace(' ', '+'); final StringBuffer response = new StringBuffer();
StringBuffer response = new StringBuffer(); final HttpClient client = new DefaultHttpClient();
HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, response.toString()); Log.d(TAG, response.toString());
return new JSONObject(response.toString()).getJSONArray("Placemark"); return new JSONObject(response.toString()).getJSONArray("Placemark");
} }
} }

View File

@@ -33,13 +33,13 @@ import com.google.android.maps.Projection;
* @author ricky barrette * @author ricky barrette
*/ */
public abstract class BaseUserOverlay extends Overlay implements GeoPointLocationListener, CompassListener { public abstract class BaseUserOverlay extends Overlay implements GeoPointLocationListener, CompassListener {
/** /**
* This thread is responsible for animating the user icon * This thread is responsible for animating the user icon
* @author ricky barrette * @author ricky barrette
*/ */
public class AnimationThread extends Thread { public class AnimationThread extends Thread {
private boolean isAborted; private boolean isAborted;
public void abort(){ public void abort(){
@@ -51,59 +51,57 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* (non-Javadoc) * (non-Javadoc)
* @see java.lang.Thread#run() * @see java.lang.Thread#run()
*/ */
@Override @Override
public void run(){ public void run(){
super.run(); super.run();
int index = 0; int index = 0;
boolean isCountingDown = false; boolean isCountingDown = false;
while (true) { while (true)
synchronized (this) { synchronized (this) {
if (isAborted) { if (isAborted)
break; break;
}
switch(index){ switch(index){
case 1: case 1:
mUserArrow = R.drawable.user_arrow_animation_2; mUserArrow = R.drawable.user_arrow_animation_2;
if(isCountingDown) if(isCountingDown)
index--;
else
index++;
try {
sleep(100l);
} catch (final InterruptedException e) {
e.printStackTrace();
}
break;
case 2:
mUserArrow = R.drawable.user_arrow_animation_3;
index--; index--;
else isCountingDown = true;
try {
sleep(200l);
} catch (final InterruptedException e) {
e.printStackTrace();
}
break;
default:
mUserArrow = R.drawable.user_arrow_animation_1;
index++; index++;
isCountingDown = false;
try { try {
sleep(100l); sleep(2000l);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} return;
break; }
case 2: break;
mUserArrow = R.drawable.user_arrow_animation_3;
index--;
isCountingDown = true;
try {
sleep(200l);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
default:
mUserArrow = R.drawable.user_arrow_animation_1;
index++;
isCountingDown = false;
try {
sleep(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
break;
} }
} }
}
} }
} }
private final String TAG = "UserOverlayBase"; private final String TAG = "UserOverlayBase";
private boolean isEnabled; private boolean isEnabled;
private int mUserArrow = R.drawable.user_arrow_animation_1; private int mUserArrow = R.drawable.user_arrow_animation_1;
@@ -111,30 +109,30 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
private float mBearing = 0; private float mBearing = 0;
private int mAccuracy; private int mAccuracy;
private GeoPoint mPoint; private GeoPoint mPoint;
private Context mContext; private final Context mContext;
private MapView mMapView; private final MapView mMapView;
private boolean isFistFix = true; private boolean isFistFix = true;
private GeoPointLocationListener mListener; private GeoPointLocationListener mListener;
public boolean isFollowingUser = true; public boolean isFollowingUser = true;
private CompasOverlay mCompass; private final CompasOverlay mCompass;
private boolean isCompassEnabled; private boolean isCompassEnabled;
private CompassListener mCompassListener; private CompassListener mCompassListener;
/** /**
* Construct a new UserOverlay * Construct a new UserOverlay
* @param mapView * @param mapView
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
public BaseUserOverlay(MapView mapView, Context context) { public BaseUserOverlay(final MapView mapView, final Context context) {
super(); super();
mContext = context; mContext = context;
mMapView = mapView; mMapView = mapView;
mCompass = new CompasOverlay(context); mCompass = new CompasOverlay(context);
mUserArrow = R.drawable.user_arrow_animation_1; mUserArrow = R.drawable.user_arrow_animation_1;
} }
/** /**
* Construct a new UserOverlayTODO Auto-generated method stub * Construct a new UserOverlayTODO Auto-generated method stub
* @param mapView * @param mapView
@@ -142,11 +140,11 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public BaseUserOverlay(MapView mapView, Context context, boolean followUser) { public BaseUserOverlay(final MapView mapView, final Context context, final boolean followUser) {
this(mapView, context); this(mapView, context);
isFollowingUser = followUser; isFollowingUser = followUser;
} }
/** /**
* Disables the compass * Disables the compass
* @author ricky barrette * @author ricky barrette
@@ -155,7 +153,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
isCompassEnabled = false; isCompassEnabled = false;
mMapView.getOverlays().remove(mCompass); mMapView.getOverlays().remove(mCompass);
} }
/** /**
* Stops location updates and removes the overlay from view * Stops location updates and removes the overlay from view
* @author ricky barrette * @author ricky barrette
@@ -169,7 +167,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
mListener.onFirstFix(false); mListener.onFirstFix(false);
mAnimationThread.abort(); mAnimationThread.abort();
} }
/** /**
* we override this methods so we can provide a drawable and a location to draw on the canvas. * we override this methods so we can provide a drawable and a location to draw on the canvas.
* (non-Javadoc) * (non-Javadoc)
@@ -180,12 +178,12 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(Canvas canvas, MapView mapView, boolean shadow){ public void draw(Canvas canvas, final MapView mapView, final boolean shadow){
if (isEnabled && mPoint != null) { if (isEnabled && mPoint != null) {
Point center = new Point(); final Point center = new Point();
Point left = new Point(); final Point left = new Point();
Projection projection = mapView.getProjection(); final Projection projection = mapView.getProjection();
GeoPoint leftGeo = GeoUtils.distanceFrom(mPoint, mAccuracy); final GeoPoint leftGeo = GeoUtils.distanceFrom(mPoint, mAccuracy);
projection.toPixels(leftGeo, left); projection.toPixels(leftGeo, left);
projection.toPixels(mPoint, center); projection.toPixels(mPoint, center);
canvas = drawAccuracyCircle(center, left, canvas); canvas = drawAccuracyCircle(center, left, canvas);
@@ -194,7 +192,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* the following log is used to demonstrate if the leftGeo point is the correct * the following log is used to demonstrate if the leftGeo point is the correct
*/ */
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, (GeoUtils.distanceKm(mPoint, leftGeo) * 1000)+"m"); Log.d(TAG, GeoUtils.distanceKm(mPoint, leftGeo) * 1000+"m");
} }
super.draw(canvas, mapView, shadow); super.draw(canvas, mapView, shadow);
} }
@@ -207,96 +205,95 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @return modified canvas * @return modified canvas
* @author ricky barrette * @author ricky barrette
*/ */
private Canvas drawAccuracyCircle(Point center, Point left, Canvas canvas) { private Canvas drawAccuracyCircle(final Point center, final Point left, final Canvas canvas) {
Paint paint = new Paint(); final Paint paint = new Paint();
/* /*
* get radius of the circle being drawn by * get radius of the circle being drawn by
*/ */
int circleRadius = center.x - left.x; int circleRadius = center.x - left.x;
if(circleRadius <= 0){ if(circleRadius <= 0)
circleRadius = left.x - center.x; circleRadius = left.x - center.x;
} /*
/* * paint a blue circle on the map
* paint a blue circle on the map */
*/ paint.setAntiAlias(true);
paint.setAntiAlias(true); paint.setStrokeWidth(2.0f);
paint.setStrokeWidth(2.0f); paint.setColor(Color.BLUE);
paint.setColor(Color.BLUE); paint.setStyle(Style.STROKE);
paint.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, circleRadius, paint);
canvas.drawCircle(center.x, center.y, circleRadius, paint);
/* /*
* fill the radius with a alpha blue * fill the radius with a alpha blue
*/ */
paint.setAlpha(30); paint.setAlpha(30);
paint.setStyle(Style.FILL); paint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, circleRadius, paint); canvas.drawCircle(center.x, center.y, circleRadius, paint);
/* /*
* for testing * for testing
* draw a dot over the left geopoint * draw a dot over the left geopoint
*/ */
if(Debug.DEBUG){ if(Debug.DEBUG){
paint.setColor(Color.RED); paint.setColor(Color.RED);
RectF oval = new RectF(left.x - 1, left.y - 1, left.x + 1, left.y + 1); final RectF oval = new RectF(left.x - 1, left.y - 1, left.x + 1, left.y + 1);
canvas.drawOval(oval, paint); canvas.drawOval(oval, paint);
} }
return canvas; return canvas;
} }
/** /**
* draws user arrow that points north based on bearing onto the supplied canvas * draws user arrow that points north based on bearing onto the supplied canvas
* @param point to draw user arrow on * @param point to draw user arrow on
* @param bearing of the device * @param bearing of the device
* @param canvas to draw on * @param canvas to draw on
* @return modified canvas * @return modified canvas
* @author ricky barrette * @author ricky barrette
*/ */
private Canvas drawUser(Point point, float bearing, Canvas canvas){ private Canvas drawUser(final Point point, final float bearing, final Canvas canvas){
Bitmap user = BitmapFactory.decodeResource(mContext.getResources(), mUserArrow); final Bitmap user = BitmapFactory.decodeResource(mContext.getResources(), mUserArrow);
Matrix matrix = new Matrix(); final Matrix matrix = new Matrix();
matrix.postRotate(bearing); matrix.postRotate(bearing);
Bitmap rotatedBmp = Bitmap.createBitmap( final Bitmap rotatedBmp = Bitmap.createBitmap(
user, user,
0, 0, 0, 0,
user.getWidth(), user.getWidth(),
user.getHeight(), user.getHeight(),
matrix, matrix,
true true
); );
canvas.drawBitmap( canvas.drawBitmap(
rotatedBmp, rotatedBmp,
point.x - (rotatedBmp.getWidth() / 2), point.x - rotatedBmp.getWidth() / 2,
point.y - (rotatedBmp.getHeight() / 2), point.y - rotatedBmp.getHeight() / 2,
null null
); );
return canvas; return canvas;
} }
/** /**
* Enables the compass * Enables the compass
* @author ricky barrette * @author ricky barrette
*/ */
public void enableCompass(){ public void enableCompass(){
if(! this.isCompassEnabled){ if(! isCompassEnabled){
this.mMapView.getOverlays().add(this.mCompass); mMapView.getOverlays().add(mCompass);
this.isCompassEnabled = true; isCompassEnabled = true;
} }
} }
/** /**
* Attempts to enable MyLocation, registering for updates from provider * Attempts to enable MyLocation, registering for updates from provider
* @author ricky barrette * @author ricky barrette
*/ */
public void enableMyLocation(){ public void enableMyLocation(){
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG,"enableMyLocation()"); Log.d(TAG,"enableMyLocation()");
if (! isEnabled) { if (! isEnabled) {
mAnimationThread = new AnimationThread(); mAnimationThread = new AnimationThread();
mAnimationThread.start(); mAnimationThread.start();
onMyLocationEnabled(); onMyLocationEnabled();
isEnabled = true; isEnabled = true;
mCompass.enable(this); mCompass.enable(this);
@@ -304,37 +301,37 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
if(mListener != null) if(mListener != null)
mListener.onFirstFix(false); mListener.onFirstFix(false);
} }
} }
/** /**
* Allows the map to follow the user * Allows the map to follow the user
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(boolean followUser){ public void followUser(final boolean followUser){
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG,"followUser()"); Log.d(TAG,"followUser()");
isFollowingUser = followUser; isFollowingUser = followUser;
} }
/** /**
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getDestination(){ public GeoPoint getDestination(){
return mCompass.getDestination(); return mCompass.getDestination();
} }
/** /**
* returns the users current bearing * returns the users current bearing
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public float getUserBearing(){ public float getUserBearing(){
return mBearing; return mBearing;
} }
/** /**
* returns the users current location * returns the users current location
* @return * @return
* @author ricky barrette * @author ricky barrette
@@ -342,9 +339,9 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
public GeoPoint getUserLocation(){ public GeoPoint getUserLocation(){
return mPoint; return mPoint;
} }
@Override @Override
public void onCompassUpdate(float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if(mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
mBearing = bearing; mBearing = bearing;
@@ -360,34 +357,32 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(GeoPoint point, int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mCompass != null) if(mCompass != null)
mCompass.setLocation(point); mCompass.setLocation(point);
/* /*
* if this is the first fix * if this is the first fix
* set map center the users location, and zoom to the max zoom level * set map center the users location, and zoom to the max zoom level
*/ */
if(point != null && isFistFix){ if(point != null && isFistFix){
mMapView.getController().setCenter(point); mMapView.getController().setCenter(point);
mMapView.getController().setZoom( (mMapView.getMaxZoomLevel() - 2) ); mMapView.getController().setZoom( mMapView.getMaxZoomLevel() - 2 );
if(mListener != null) if(mListener != null)
mListener.onFirstFix(true); mListener.onFirstFix(true);
isFistFix = false; isFistFix = false;
} }
//update the users point, and accuracy for the UI //update the users point, and accuracy for the UI
mPoint = point; mPoint = point;
mAccuracy = accuracy; mAccuracy = accuracy;
mMapView.invalidate(); mMapView.invalidate();
if(mListener != null){ if(mListener != null)
mListener.onLocationChanged(point, accuracy); mListener.onLocationChanged(point, accuracy);
}
if (isFollowingUser)
if (isFollowingUser) {
panToUserIfOffMap(point); panToUserIfOffMap(point);
}
} }
/** /**
@@ -397,43 +392,41 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
public abstract void onMyLocationDisabled(); public abstract void onMyLocationDisabled();
/** /**
* Called when the enableMyLocation() is called. This is where you want to ask your location provider for updates * Called when the enableMyLocation() is called. This is where you want to ask your location provider for updates
* @author ricky barrette * @author ricky barrette
*/ */
public abstract void onMyLocationEnabled(); public abstract void onMyLocationEnabled();
/** /**
* pans the map view if the user is off screen. * pans the map view if the user is off screen.
* @author ricky barrette * @author ricky barrette
*/ */
private void panToUserIfOffMap(GeoPoint user) { private void panToUserIfOffMap(final GeoPoint user) {
GeoPoint center = mMapView.getMapCenter(); final GeoPoint center = mMapView.getMapCenter();
double distance = GeoUtils.distanceKm(center, user); final double distance = GeoUtils.distanceKm(center, user);
double distanceLat = GeoUtils.distanceKm(center, new GeoPoint((center.getLatitudeE6() + (int) (mMapView.getLatitudeSpan() / 2)), center.getLongitudeE6())); final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + mMapView.getLatitudeSpan() / 2, center.getLongitudeE6()));
double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), (center.getLongitudeE6() + (int) (mMapView.getLongitudeSpan() / 2)))); final double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), center.getLongitudeE6() + mMapView.getLongitudeSpan() / 2));
double whichIsGreater = (distanceLat > distanceLon) ? distanceLat : distanceLon; final double whichIsGreater = distanceLat > distanceLon ? distanceLat : distanceLon;
/** /**
* if the user is one the map, keep them their * if the user is one the map, keep them their
* else don't pan to user unless they pan pack to them * else don't pan to user unless they pan pack to them
*/ */
if( ! (distance > whichIsGreater) ) if( ! (distance > whichIsGreater) )
if (distance > distanceLat || distance > distanceLon){ if (distance > distanceLat || distance > distanceLon)
mMapView.getController().animateTo(user); mMapView.getController().animateTo(user);
}
} }
/** /**
* Attempts to register the listener for location updates * Attempts to register the listener for location updates
* @param listener * @param listener
* @author Ricky Barrette * @author Ricky Barrette
*/ */
public void registerListener(GeoPointLocationListener listener){ public void registerListener(final GeoPointLocationListener listener){
Log.d(TAG,"registerListener()"); Log.d(TAG,"registerListener()");
if (mListener == null){ if (mListener == null)
mListener = listener; mListener = listener;
}
} }
/** /**
@@ -444,7 +437,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(int needleResId, int backgroundResId, int x, int y) { public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y) {
mCompass.setDrawables(needleResId, backgroundResId, x, y); mCompass.setDrawables(needleResId, backgroundResId, x, y);
} }
@@ -453,19 +446,19 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(CompassListener listener){ public void setCompassListener(final CompassListener listener){
mCompassListener = listener; mCompassListener = listener;
} }
/** /**
* Sets the destination for the compass * Sets the destination for the compass
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
if(mCompass != null) if(mCompass != null)
mCompass.setDestination(destination); mCompass.setDestination(destination);
} }
/** /**
* UnResgisters the listener. after this call you will no longer get location updates * UnResgisters the listener. after this call you will no longer get location updates
* @author Ricky Barrette * @author Ricky Barrette

View File

@@ -45,20 +45,20 @@ public class CompasOverlay extends Overlay implements CompassListener {
* Creates a new CompasOverlay * Creates a new CompasOverlay
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context) { public CompasOverlay(final Context context) {
mContext = context; mContext = context;
mCompassSensor = new CompassSensor(context); mCompassSensor = new CompassSensor(context);
mX = convertDipToPx(40); mX = convertDipToPx(40);
mY = mX; mY = mX;
} }
/** /**
* Creates a new CompasOverlay * Creates a new CompasOverlay
* @param context * @param context
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context, GeoPoint destination){ public CompasOverlay(final Context context, final GeoPoint destination){
this(context); this(context);
mDestination = destination; mDestination = destination;
} }
@@ -73,14 +73,14 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y dip * @param y dip
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context, GeoPoint destination, int needleResId, int backgroundResId, int x, int y){ public CompasOverlay(final Context context, final GeoPoint destination, final int needleResId, final int backgroundResId, final int x, final int y){
this(context, destination); this(context, destination);
mX = convertDipToPx(x); mX = convertDipToPx(x);
mY = convertDipToPx(y); mY = convertDipToPx(y);
mNeedleResId = needleResId; mNeedleResId = needleResId;
mBackgroundResId = backgroundResId; mBackgroundResId = backgroundResId;
} }
/** /**
* Creates a new CompasOverlay * Creates a new CompasOverlay
* @param context * @param context
@@ -90,7 +90,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context, int needleResId, int backgroundResId, int x, int y){ public CompasOverlay(final Context context, final int needleResId, final int backgroundResId, final int x, final int y){
this(context, null, needleResId, backgroundResId, x, y); this(context, null, needleResId, backgroundResId, x, y);
} }
@@ -100,8 +100,8 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @return px * @return px
* @author ricky barrette * @author ricky barrette
*/ */
private int convertDipToPx(int i) { private int convertDipToPx(final int i) {
Resources r = mContext.getResources(); final Resources r = mContext.getResources();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, r.getDisplayMetrics()); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, r.getDisplayMetrics());
} }
@@ -114,7 +114,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
mCompassSensor.disable(); mCompassSensor.disable();
mListener = null; mListener = null;
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean) * @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean)
@@ -122,43 +122,43 @@ public class CompasOverlay extends Overlay implements CompassListener {
*/ */
@Override @Override
public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) { public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
if(isEnabled){ if(isEnabled){
//set the center of the compass in the top left corner of the screen //set the center of the compass in the top left corner of the screen
Point point = new Point(); final Point point = new Point();
point.set(mX, mY); point.set(mX, mY);
//draw compass background //draw compass background
Bitmap compass = BitmapFactory.decodeResource( mContext.getResources(), mBackgroundResId); final Bitmap compass = BitmapFactory.decodeResource( mContext.getResources(), mBackgroundResId);
canvas.drawBitmap(compass, canvas.drawBitmap(compass,
point.x - (compass.getWidth() / 2), point.x - compass.getWidth() / 2,
point.y - (compass.getHeight() / 2), point.y - compass.getHeight() / 2,
null null
); );
//draw the compass needle //draw the compass needle
Bitmap arrowBitmap = BitmapFactory.decodeResource( mContext.getResources(), mNeedleResId); final Bitmap arrowBitmap = BitmapFactory.decodeResource( mContext.getResources(), mNeedleResId);
Matrix matrix = new Matrix(); final Matrix matrix = new Matrix();
matrix.postRotate(GeoUtils.calculateBearing(mLocation, mDestination, mBearing)); matrix.postRotate(GeoUtils.calculateBearing(mLocation, mDestination, mBearing));
Bitmap rotatedBmp = Bitmap.createBitmap( final Bitmap rotatedBmp = Bitmap.createBitmap(
arrowBitmap, arrowBitmap,
0, 0, 0, 0,
arrowBitmap.getWidth(), arrowBitmap.getWidth(),
arrowBitmap.getHeight(), arrowBitmap.getHeight(),
matrix, matrix,
true true
); );
canvas.drawBitmap( canvas.drawBitmap(
rotatedBmp, rotatedBmp,
point.x - (rotatedBmp.getWidth() / 2), point.x - rotatedBmp.getWidth() / 2,
point.y - (rotatedBmp.getHeight() / 2), point.y - rotatedBmp.getHeight() / 2,
null null
); );
mapView.invalidate(); mapView.invalidate();
} }
super.draw(canvas, mapView, shadow); super.draw(canvas, mapView, shadow);
} }
/** /**
* Enables the compass overlay * Enables the compass overlay
* @author ricky barrette * @author ricky barrette
@@ -169,17 +169,17 @@ public class CompasOverlay extends Overlay implements CompassListener {
mCompassSensor.enable(this); mCompassSensor.enable(this);
} }
} }
/** /**
* Enables the compass overlay * Enables the compass overlay
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(CompassListener listener){ public void enable(final CompassListener listener){
mListener = listener; mListener = listener;
enable(); enable();
} }
/** /**
* @return the current bearing * @return the current bearing
* @author ricky barrette * @author ricky barrette
@@ -187,7 +187,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
public float getBearing(){ public float getBearing(){
return mBearing; return mBearing;
} }
/** /**
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
@@ -203,24 +203,24 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onCompassUpdate(float bearing) { public void onCompassUpdate(final float bearing) {
mBearing = bearing; mBearing = bearing;
/* /*
* pass it down the chain * pass it down the chain
*/ */
if(mListener != null) if(mListener != null)
mListener.onCompassUpdate(bearing); mListener.onCompassUpdate(bearing);
} }
/** /**
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
mDestination = destination; mDestination = destination;
} }
/** /**
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
@@ -228,18 +228,18 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y dip * @param y dip
* @author ricky barrette * @author ricky barrette
*/ */
public void setDrawables(int needleResId, int backgroundResId, int x, int y){ public void setDrawables(final int needleResId, final int backgroundResId, final int x, final int y){
mX = convertDipToPx(x); mX = convertDipToPx(x);
mY = convertDipToPx(y); mY = convertDipToPx(y);
mNeedleResId = needleResId; mNeedleResId = needleResId;
mBackgroundResId = backgroundResId; mBackgroundResId = backgroundResId;
} }
/** /**
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocation(GeoPoint location){ public void setLocation(final GeoPoint location){
mLocation = location; mLocation = location;
} }

View File

@@ -30,14 +30,14 @@ import com.google.android.maps.GeoPoint;
* @author ricky barrette * @author ricky barrette
*/ */
public class DirectionsOverlay { public class DirectionsOverlay {
/** /**
* @author ricky barrette * @author ricky barrette
*/ */
public interface OnDirectionsCompleteListener{ public interface OnDirectionsCompleteListener{
public void onDirectionsComplete(DirectionsOverlay directionsOverlay); public void onDirectionsComplete(DirectionsOverlay directionsOverlay);
} }
private static final String TAG = "DirectionsOverlay"; private static final String TAG = "DirectionsOverlay";
private ArrayList<PathOverlay> mPath; private ArrayList<PathOverlay> mPath;
private ArrayList<String> mDirections; private ArrayList<String> mDirections;
@@ -48,24 +48,24 @@ public class DirectionsOverlay {
private ArrayList<String> mDistance; private ArrayList<String> mDistance;
private ArrayList<String> mDuration; private ArrayList<String> mDuration;
private ArrayList<String> mWarnings; private ArrayList<String> mWarnings;
/** /**
* Downloads and Creates a new DirectionsOverlay from the provided points * Downloads and Creates a new DirectionsOverlay from the provided points
* @param origin point * @param origin point
* @param destination point * @param destination point
* @author ricky barrette * @author ricky barrette
* @throws IOException * @throws IOException
* @throws ClientProtocolException * @throws ClientProtocolException
* @throws IllegalStateException * @throws IllegalStateException
* @throws JSONException * @throws JSONException
*/ */
public DirectionsOverlay(final MapView map, final GeoPoint origin, final GeoPoint destination, final OnDirectionsCompleteListener listener) throws IllegalStateException, ClientProtocolException, IOException, JSONException { public DirectionsOverlay(final MapView map, final GeoPoint origin, final GeoPoint destination, final OnDirectionsCompleteListener listener) throws IllegalStateException, ClientProtocolException, IOException, JSONException {
mMapView = map; mMapView = map;
mListener = listener; mListener = listener;
String json = downloadJSON(generateUrl(origin, destination)); final String json = downloadJSON(generateUrl(origin, destination));
drawPath(json); drawPath(json);
} }
/** /**
* Creates a new DirectionsOverlay from the provided String JSON * Creates a new DirectionsOverlay from the provided String JSON
* @param json * @param json
@@ -77,65 +77,66 @@ public class DirectionsOverlay {
mMapView = map; mMapView = map;
drawPath(json); drawPath(json);
} }
/** /**
* Deocodes googles polyline * Deocodes googles polyline
* @param encoded * @param encoded
* @return a list of geopoints representing the path * @return a list of geopoints representing the path
* @author Mark McClure http://facstaff.unca.edu/mcmcclur/googlemaps/encodepolyline/ * @author Mark McClure http://facstaff.unca.edu/mcmcclur/googlemaps/encodepolyline/
* @author ricky barrette * @author ricky barrette
* @throws JSONException * @throws JSONException
*/ */
private void decodePoly(final JSONObject step) throws JSONException { private void decodePoly(final JSONObject step) throws JSONException {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, "decodePoly"); Log.d(TAG, "decodePoly");
String encoded = step.getJSONObject("polyline").getString("points"); final String encoded = step.getJSONObject("polyline").getString("points");
int index = 0, len = encoded.length(); int index = 0;
int lat = 0, lng = 0; final int len = encoded.length();
int lat = 0, lng = 0;
GeoPoint last = null; GeoPoint last = null;
while (index < len) { while (index < len) {
int b, shift = 0, result = 0; int b, shift = 0, result = 0;
do { do {
b = encoded.charAt(index++) - 63; b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift; result |= (b & 0x1f) << shift;
shift += 5; shift += 5;
} while (b >= 0x20); } while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); final int dlat = (result & 1) != 0 ? ~(result >> 1) : result >> 1;
lat += dlat; lat += dlat;
shift = 0; shift = 0;
result = 0; result = 0;
do { do {
b = encoded.charAt(index++) - 63; b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift; result |= (b & 0x1f) << shift;
shift += 5; shift += 5;
} while (b >= 0x20); } while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); final int dlng = (result & 1) != 0 ? ~(result >> 1) : result >> 1;
lng += dlng; lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6), (int) (((double) lng / 1E5) * 1E6)); final GeoPoint p = new GeoPoint((int) (lat / 1E5 * 1E6), (int) (lng / 1E5 * 1E6));
if(Debug.DEBUG){ if(Debug.DEBUG){
Log.d(TAG, "current = "+ p.toString()); Log.d(TAG, "current = "+ p.toString());
if(last != null) if(last != null)
Log.d(TAG, "last = "+ last.toString()); Log.d(TAG, "last = "+ last.toString());
} }
if(last != null) if(last != null)
mPath.add(new PathOverlay(last, p, Color.RED)); mPath.add(new PathOverlay(last, p, Color.RED));
// else // else
// mPath.add(new PathOverlay(p, 5, Color.GREEN)); // mPath.add(new PathOverlay(p, 5, Color.GREEN));
last = p; last = p;
} }
} }
/** /**
* Downloads Google Directions JSON from the Internet * Downloads Google Directions JSON from the Internet
* @param url * @param url
* @return * @return
* @throws IllegalStateException * @throws IllegalStateException
@@ -148,21 +149,21 @@ public class DirectionsOverlay {
Log.d(TAG, url); Log.d(TAG, url);
if(url == null) if(url == null)
throw new NullPointerException(); throw new NullPointerException();
StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
return response.toString(); return response.toString();
} }
/** /**
* Creates a new DirectionsOverlay from the json provided * Creates a new DirectionsOverlay from the json provided
* @param json of Google Directions API * @param json of Google Directions API
* @author ricky barrette * @author ricky barrette
* @return * @return
* @throws JSONException * @throws JSONException
*/ */
public void drawPath(final String json) throws JSONException{ public void drawPath(final String json) throws JSONException{
if(Debug.DEBUG){ if(Debug.DEBUG){
@@ -174,75 +175,75 @@ public class DirectionsOverlay {
mPoints = new ArrayList<GeoPoint>(); mPoints = new ArrayList<GeoPoint>();
mDistance = new ArrayList<String>(); mDistance = new ArrayList<String>();
mDuration = new ArrayList<String>(); mDuration = new ArrayList<String>();
//get first route //get first route
JSONObject route = new JSONObject(json).getJSONArray("routes").getJSONObject(0); final JSONObject route = new JSONObject(json).getJSONArray("routes").getJSONObject(0);
mCopyRights = route.getString("copyrights"); mCopyRights = route.getString("copyrights");
//route.getString("status"); //route.getString("status");
JSONObject leg = route.getJSONArray("legs").getJSONObject(0); final JSONObject leg = route.getJSONArray("legs").getJSONObject(0);
getDistance(leg); getDistance(leg);
getDuration(leg); getDuration(leg);
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("start_location")), 12, Color.GREEN)); // mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("start_location")), 12, Color.GREEN));
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("end_location")), 12, Color.RED)); // mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("end_location")), 12, Color.RED));
leg.getString("start_address"); leg.getString("start_address");
leg.getString("end_address"); leg.getString("end_address");
// JSONArray warnings = leg.getJSONArray("warnings"); // JSONArray warnings = leg.getJSONArray("warnings");
// for(int i = 0; i < warnings.length(); i++){ // for(int i = 0; i < warnings.length(); i++){
// mWarnings.add(warnings.get)w // mWarnings.add(warnings.get)w
// }w // }w
/* /*
* here we will parse the steps of the directions * here we will parse the steps of the directions
*/ */
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, "processing steps"); Log.d(TAG, "processing steps");
JSONArray steps = leg.getJSONArray("steps"); final JSONArray steps = leg.getJSONArray("steps");
JSONObject step = null; JSONObject step = null;
for(int i = 0; i < steps.length(); i++){ for(int i = 0; i < steps.length(); i++){
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, "step "+i); Log.d(TAG, "step "+i);
step = steps.getJSONObject(i); step = steps.getJSONObject(i);
if(Debug.DEBUG){ if(Debug.DEBUG){
Log.d(TAG, "start "+getGeoPoint(step.getJSONObject("start_location")).toString()); Log.d(TAG, "start "+getGeoPoint(step.getJSONObject("start_location")).toString());
Log.d(TAG, "end "+getGeoPoint(step.getJSONObject("end_location")).toString()); Log.d(TAG, "end "+getGeoPoint(step.getJSONObject("end_location")).toString());
} }
// if(Debug.DEBUG) // if(Debug.DEBUG)
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(step.getJSONObject("start_location")), getGeoPoint(step.getJSONObject("end_location")), Color.MAGENTA)); // mMapView.getOverlays().add(new PathOverlay(getGeoPoint(step.getJSONObject("start_location")), getGeoPoint(step.getJSONObject("end_location")), Color.MAGENTA));
decodePoly(step); decodePoly(step);
mDuration.add(getDuration(step)); mDuration.add(getDuration(step));
mDistance.add(getDistance(step)); mDistance.add(getDistance(step));
mDirections.add(step.getString("html_instructions")); mDirections.add(step.getString("html_instructions"));
// Log.d("TEST", step.getString("html_instructions")); // Log.d("TEST", step.getString("html_instructions"));
mPoints.add(getGeoPoint(step.getJSONObject("start_location"))); mPoints.add(getGeoPoint(step.getJSONObject("start_location")));
} }
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, "finished parsing"); Log.d(TAG, "finished parsing");
if(mMapView != null){ if(mMapView != null){
mMapView.getOverlays().addAll(mPath); mMapView.getOverlays().addAll(mPath);
mMapView.postInvalidate(); mMapView.postInvalidate();
} }
if(mListener != null) if(mListener != null)
mListener.onDirectionsComplete(DirectionsOverlay.this); mListener.onDirectionsComplete(DirectionsOverlay.this);
} }
/** /**
* @param origin * @param origin
* @param destination * @param destination
* @return The Google API url for our directions * @return The Google API url for our directions
* @author ricky barrette * @author ricky barrette
*/ */
private String generateUrl(final GeoPoint origin, final GeoPoint destination){ private String generateUrl(final GeoPoint origin, final GeoPoint destination){
@@ -256,7 +257,7 @@ public class DirectionsOverlay {
Double.toString(destination.getLongitudeE6() / 1.0E6)+ Double.toString(destination.getLongitudeE6() / 1.0E6)+
"&sensor=true&mode=walking"; "&sensor=true&mode=walking";
} }
/** /**
* @return * @return
* @author ricky barrette * @author ricky barrette
@@ -264,7 +265,7 @@ public class DirectionsOverlay {
public String getCopyrights(){ public String getCopyrights(){
return mCopyRights; return mCopyRights;
} }
/** /**
* @return * @return
* @author ricky barrette * @author ricky barrette
@@ -282,7 +283,7 @@ public class DirectionsOverlay {
private String getDistance(final JSONObject step) throws JSONException{ private String getDistance(final JSONObject step) throws JSONException{
return step.getJSONObject("distance").getString("text"); return step.getJSONObject("distance").getString("text");
} }
/** /**
* @return * @return
* @author ricky barrette * @author ricky barrette
@@ -293,7 +294,7 @@ public class DirectionsOverlay {
/** /**
* @param step * @param step
* @return the duration of a step * @return the duration of a step
* @throws JSONException * @throws JSONException
* @author ricky barrette * @author ricky barrette
*/ */
@@ -327,7 +328,7 @@ public class DirectionsOverlay {
public ArrayList<PathOverlay> getPath(){ public ArrayList<PathOverlay> getPath(){
return mPath; return mPath;
} }
/** /**
* @return * @return
* @author ricky barrette * @author ricky barrette
@@ -349,6 +350,6 @@ public class DirectionsOverlay {
* @author ricky barrette * @author ricky barrette
*/ */
public void removePath() { public void removePath() {
if(mMapView.getOverlays().removeAll(mPath)); if(mMapView.getOverlays().removeAll(mPath));
} }
} }

View File

@@ -41,7 +41,7 @@ public final class PathOverlay extends Overlay {
mMode = PATH; mMode = PATH;
mRadius = 0; mRadius = 0;
} }
/** /**
* Creates a new PathOverlay in point mode. This is used to draw end points. * Creates a new PathOverlay in point mode. This is used to draw end points.
* @param point * @param point
@@ -56,29 +56,29 @@ public final class PathOverlay extends Overlay {
mEnd = mStart; mEnd = mStart;
mColor = color; mColor = color;
} }
/** /**
* *
* @param canvas canvas to be drawn on * @param canvas canvas to be drawn on
* @param mapView * @param mapView
* @param shadow * @param shadow
* @param when * @param when
*/ */
@Override @Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) { public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
final Projection projection = mapView.getProjection(); final Projection projection = mapView.getProjection();
final Paint paint = new Paint(); final Paint paint = new Paint();
paint.setColor(mColor); paint.setColor(mColor);
paint.setAntiAlias(true); paint.setAntiAlias(true);
Point point = new Point(); final Point point = new Point();
projection.toPixels(mStart, point); projection.toPixels(mStart, point);
switch (mMode){ switch (mMode){
case POINT: case POINT:
RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius); final RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius);
canvas.drawOval(oval, paint); canvas.drawOval(oval, paint);
case PATH: case PATH:
Point point2 = new Point(); final Point point2 = new Point();
projection.toPixels(mEnd, point2); projection.toPixels(mEnd, point2);
paint.setStrokeWidth(5); paint.setStrokeWidth(5);
paint.setAlpha(120); paint.setAlpha(120);
@@ -86,20 +86,20 @@ public final class PathOverlay extends Overlay {
} }
super.draw(canvas, mapView, shadow); super.draw(canvas, mapView, shadow);
} }
/** /**
* @return the end point of this path * @return the end point of this path
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getEndPoint(){ public GeoPoint getEndPoint(){
return this.mEnd; return mEnd;
} }
/** /**
* @return the start point of this path * @return the start point of this path
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getStartPoint(){ public GeoPoint getStartPoint(){
return this.mStart; return mStart;
} }
} }

View File

@@ -1,7 +1,7 @@
/** /**
* @author Twenty Codes * @author Twenty Codes
* @author ricky barrette * @author ricky barrette
*/ */
package com.TwentyCodes.android.overlays; package com.TwentyCodes.android.overlays;
@@ -21,7 +21,7 @@ import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection; import com.google.android.maps.Projection;
/** /**
* This class will used to draw a radius of a specified size in a specified location, then inserted into * This class will used to draw a radius of a specified size in a specified location, then inserted into
* an overlay list to be displayed a map * an overlay list to be displayed a map
* @author ricky barrette * @author ricky barrette
*/ */
@@ -33,32 +33,32 @@ public class RadiusOverlay extends Overlay{
private int mColor = Color.GREEN; private int mColor = Color.GREEN;
private GeoPoint mRadiusPoint; private GeoPoint mRadiusPoint;
private OnLocationSelectedListener mListener; private OnLocationSelectedListener mListener;
/** /**
* Creates a new RadiusOverlay * Creates a new RadiusOverlay
* @author ricky barrette * @author ricky barrette
*/ */
public RadiusOverlay(){ public RadiusOverlay(){
} }
/** /**
* Creates a new RadiusOverlay object that can be inserted into an overlay list. * Creates a new RadiusOverlay object that can be inserted into an overlay list.
* @param point center of radius geopoint * @param point center of radius geopoint
* @param radius radius in meters * @param radius radius in meters
* @param color desired color of the radius from Color API * @param color desired color of the radius from Color API
* @author ricky barrette * @author ricky barrette
*/ */
public RadiusOverlay(GeoPoint point, float radius, int color) { public RadiusOverlay(final GeoPoint point, final float radius, final int color) {
mPoint = point; mPoint = point;
mRadius = radius; mRadius = radius;
mColor = color; mColor = color;
} }
/** /**
* draws a specific radius on the mapview that is handed to it * draws a specific radius on the mapview that is handed to it
* @param canvas canvas to be drawn on * @param canvas canvas to be drawn on
* @param mapView * @param mapView
* @param shadow * @param shadow
* @param when * @param when
*/ */
@Override @Override
@@ -68,44 +68,43 @@ public class RadiusOverlay extends Overlay{
final Point center = new Point(); final Point center = new Point();
final Point left = new Point(); final Point left = new Point();
final Projection projection = mapView.getProjection(); final Projection projection = mapView.getProjection();
/* /*
* Calculate a geopoint that is "radius" meters away from geopoint point and * Calculate a geopoint that is "radius" meters away from geopoint point and
* convert the given GeoPoint and leftGeo to onscreen pixel coordinates, * convert the given GeoPoint and leftGeo to onscreen pixel coordinates,
* relative to the top-left of the MapView that provided this Projection. * relative to the top-left of the MapView that provided this Projection.
*/ */
mRadiusPoint = GeoUtils.distanceFrom(mPoint , mRadius); mRadiusPoint = GeoUtils.distanceFrom(mPoint , mRadius);
projection.toPixels(mRadiusPoint, left); projection.toPixels(mRadiusPoint, left);
projection.toPixels(mPoint, center); projection.toPixels(mPoint, center);
/* /*
* get radius of the circle being drawn by * get radius of the circle being drawn by
*/ */
int circleRadius = center.x - left.x; int circleRadius = center.x - left.x;
if(circleRadius <= 0){ if(circleRadius <= 0)
circleRadius = left.x - center.x; circleRadius = left.x - center.x;
}
/*
/* * paint a circle on the map
* paint a circle on the map */
*/ paint.setAntiAlias(true);
paint.setAntiAlias(true); paint.setStrokeWidth(2.0f);
paint.setStrokeWidth(2.0f); paint.setColor(mColor);
paint.setColor(mColor); paint.setStyle(Style.STROKE);
paint.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, circleRadius, paint);
canvas.drawCircle(center.x, center.y, circleRadius, paint);
//draw a dot over the geopoint
//draw a dot over the geopoint final RectF oval = new RectF(center.x - 2, center.y - 2, center.x + 2, center.y + 2);
RectF oval = new RectF(center.x - 2, center.y - 2, center.x + 2, center.y + 2);
canvas.drawOval(oval, paint); canvas.drawOval(oval, paint);
//fill the radius with a nice green //fill the radius with a nice green
paint.setAlpha(25); paint.setAlpha(25);
paint.setStyle(Style.FILL); paint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, circleRadius, paint); canvas.drawCircle(center.x, center.y, circleRadius, paint);
} }
} }
/** /**
* @return the selected location * @return the selected location
* @author ricky barrette * @author ricky barrette
@@ -113,12 +112,17 @@ public class RadiusOverlay extends Overlay{
public GeoPoint getLocation(){ public GeoPoint getLocation(){
return mPoint; return mPoint;
} }
public int getZoomLevel() {
// GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius)
return 0;
}
@Override @Override
public boolean onTap(GeoPoint p, MapView mapView) { public boolean onTap(final GeoPoint p, final MapView mapView) {
mPoint = p; mPoint = p;
if(this.mListener != null) if(mListener != null)
this.mListener.onLocationSelected(p); mListener.onLocationSelected(p);
return super.onTap(p, mapView); return super.onTap(p, mapView);
} }
@@ -126,33 +130,28 @@ public class RadiusOverlay extends Overlay{
* @param color * @param color
* @author ricky barrette * @author ricky barrette
*/ */
public void setColor(int color){ public void setColor(final int color){
mColor = color; mColor = color;
} }
/** /**
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocation(GeoPoint location){ public void setLocation(final GeoPoint location){
mPoint = location; mPoint = location;
} }
public void setLocationSelectedListener(final OnLocationSelectedListener listener) {
mListener = listener;
}
/** /**
* @param radius in meters * @param radius in meters
* @author ricky barrette * @author ricky barrette
* @param radius * @param radius
*/ */
public void setRadius(int radius){ public void setRadius(final int radius){
mRadius = radius; mRadius = radius;
} }
public int getZoomLevel() {
// GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius)
return 0;
}
public void setLocationSelectedListener(OnLocationSelectedListener listener) {
this.mListener = listener;
}
} }

View File

@@ -17,12 +17,12 @@ import com.google.android.maps.MapView;
public class SkyHookUserOverlay extends BaseUserOverlay{ public class SkyHookUserOverlay extends BaseUserOverlay{
private final SkyHook mSkyHook; private final SkyHook mSkyHook;
public SkyHookUserOverlay(MapView mapView, Context context) { public SkyHookUserOverlay(final MapView mapView, final Context context) {
super(mapView, context); super(mapView, context);
mSkyHook = new SkyHook(context); mSkyHook = new SkyHook(context);
} }
/** /**
* Construct a new SkyHookUserOverlay * Construct a new SkyHookUserOverlay
* @param mapView * @param mapView
@@ -30,11 +30,16 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHookUserOverlay(MapView mapView, Context context, boolean followUser) { public SkyHookUserOverlay(final MapView mapView, final Context context, final boolean followUser) {
super(mapView, context, followUser); super(mapView, context, followUser);
mSkyHook = new SkyHook(context); mSkyHook = new SkyHook(context);
} }
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
/** /**
* Called when the location provider needs to be disabled * Called when the location provider needs to be disabled
* (non-Javadoc) * (non-Javadoc)
@@ -56,9 +61,4 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
mSkyHook.getUpdates(); mSkyHook.getUpdates();
} }
@Override
public void onFirstFix(boolean isFistFix) {
// unused
}
} }

View File

@@ -11,23 +11,28 @@ import com.TwentyCodes.android.location.AndroidGPS;
import com.google.android.maps.MapView; import com.google.android.maps.MapView;
/** /**
* This is the standard version of the UserOverlay. * This is the standard version of the UserOverlay.
* @author ricky barrette * @author ricky barrette
*/ */
public class UserOverlay extends BaseUserOverlay{ public class UserOverlay extends BaseUserOverlay{
private final AndroidGPS mAndroidGPS; private final AndroidGPS mAndroidGPS;
public UserOverlay(MapView mapView, Context context) { public UserOverlay(final MapView mapView, final Context context) {
super(mapView, context); super(mapView, context);
mAndroidGPS = new AndroidGPS(context); mAndroidGPS = new AndroidGPS(context);
} }
public UserOverlay(MapView mapView, Context context, boolean followUser) { public UserOverlay(final MapView mapView, final Context context, final boolean followUser) {
super(mapView, context, followUser); super(mapView, context, followUser);
mAndroidGPS = new AndroidGPS(context); mAndroidGPS = new AndroidGPS(context);
} }
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
@Override @Override
public void onMyLocationDisabled() { public void onMyLocationDisabled() {
mAndroidGPS.disableLocationUpdates(); mAndroidGPS.disableLocationUpdates();
@@ -38,9 +43,4 @@ public class UserOverlay extends BaseUserOverlay{
mAndroidGPS.enableLocationUpdates(this); mAndroidGPS.enableLocationUpdates(this);
} }
@Override
public void onFirstFix(boolean isFistFix) {
// unused
}
} }