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-sdk
android:minSdkVersion="4"
android:targetSdkVersion="11" />
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-feature
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"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#000000"/>
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#000000"
android:layout_gravity="right"
android:paddingRight="10dip"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20dip" />
<TextView
android:id="@+id/TextView02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingRight="10dip"
android:textColor="#000000"
android:textSize="20dip" />
</LinearLayout>

View File

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

View File

@@ -26,22 +26,40 @@ import com.skyhookwireless.wps.XPS;
* @author ricky barrette
*/
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 USERNAME = "cjyh95q32gsc";
public static final String USERNAME_FOR_TESTING = "twentycodes";
public static final String REALM = "TwentyCodes";
public static final int LOCATION_MESSAGE = 1;
public static final int ERROR_MESSAGE = 2;
public static final int DONE_MESSAGE = 3;
private final XPScallback mXPScallback = new XPScallback();
private final XPS mXps;
private final Context mContext;
public static final int ERROR_MESSAGE = 2;
public static final int DONE_MESSAGE = 3;
private final XPScallback mXPScallback = new XPScallback();
private final XPS mXps;
private final Context mContext;
private GeoPointLocationListener mListener;
private long mPeriod = 0l; //period is in milliseconds for periodic updates
private int mIterations = 0;
private long mPeriod = 0l; //period is in milliseconds for periodic updates
private final int mIterations = 0;
private WPSAuthentication mWPSAuthentication;
private Handler mHandler;
private static Handler mHandler;
private boolean isPeriodicEnabled;
private boolean hasLocation;
protected AndroidGPS mSkyHookFallback = null;
@@ -49,95 +67,79 @@ public class SkyHook implements GeoPointLocationListener{
private boolean isFallBackScheduled = false;
private boolean isEnabled = false;
private boolean isUnauthorized = false;
private boolean isFirstFix;
/*
* 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.
*/
private final Runnable mFallBack = new Runnable() {
@Override
public void run() {
mHandler.removeCallbacks(mFallBack);
Log.d(TAG,"skyhook, "+ (hasLocation ? "is" : "isn't") +" working!");
if((! hasLocation) && (mSkyHookFallback == null) && isEnabled){
Log.d(TAG,"falling back on android");
mSkyHookFallback = new AndroidGPS(mContext);
mSkyHookFallback.enableLocationUpdates(SkyHook.this);
/*
* Schedule another check, if skyhook is still enabled
*/
if(mXps != null)
mHandler.postDelayed(mFallBack, mFallBackDelay );
} else {
Log.d(TAG,"already fell back on android");
if(mSkyHookFallback != null) {
Log.d(TAG,"got location, picking up the slack");
mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null;
}
isFallBackScheduled = false;
}
}
};
/*
* this runnable keeps skyhook working!
*/
if(! hasLocation && mSkyHookFallback == null && isEnabled){
Log.d(TAG,"falling back on android");
mSkyHookFallback = new AndroidGPS(mContext);
mSkyHookFallback.enableLocationUpdates(SkyHook.this);
/*
* Schedule another check, if skyhook is still enabled
*/
if(mXps != null)
mHandler.postDelayed(mFallBack, mFallBackDelay );
} else {
Log.d(TAG,"already fell back on android");
if(mSkyHookFallback != null) {
Log.d(TAG,"got location, picking up the slack");
mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null;
}
isFallBackScheduled = false;
}
}
};
/*
* this runnable keeps skyhook working!
*/
private final Runnable mPeriodicUpdates = new Runnable() {
@Override
public void run() {
if(Debug.DEBUG)
Log.d(TAG,"geting location");
mXps.getXPSLocation(mWPSAuthentication, mIterations, XPS.EXACT_ACCURACY, mXPScallback);
}
};
private class XPScallback implements WPSPeriodicLocationCallback {
@Override
public void done() {
mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE));
mXps.getXPSLocation(mWPSAuthentication, mIterations, XPS.EXACT_ACCURACY, mXPScallback);
}
};
@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
* @param context
* @author ricky barrette
*/
public SkyHook(Context context) {
public SkyHook(final Context context) {
mXps = new XPS(context);
mContext = context;
// initialize the Handler which will display location data
// in the text view. we use a Handler because UI updates
// must occur in the UI thread
setUIHandler();
isFirstFix = true;
// in the text view. we use a Handler because UI updates
// must occur in the UI thread
setUIHandler();
isFirstFix = true;
}
/**
* Constructors a new skyhook object
* @param context
* @param period between location updates in milliseconds
* @author ricky barrette
*/
public SkyHook(Context context, long period) {
public SkyHook(final Context context, final long period) {
this(context);
mPeriod = period;
}
/**
* request current user location, note that the listeners onLocationChanged() will be call multiple times.
* updates will stop once an accurate location is determined.
@@ -150,7 +152,7 @@ public class SkyHook implements GeoPointLocationListener{
mHandler.post(mPeriodicUpdates);
}
}
/**
* Attempts to register the the listener for periodic updates
* @author Ricky Barrette
@@ -158,17 +160,17 @@ public class SkyHook implements GeoPointLocationListener{
public void getUpdates(){
Log.d(TAG,"getUpdates()");
if (mListener != null) {
if(Debug.DEBUG)
Log.i(TAG, "username: " + SkyHookRegistration.getUserName(mContext));
mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM);
isPeriodicEnabled = true;
mHandler.post(mPeriodicUpdates);
isEnabled = true;
}
}
/**
* @return true is skyhook is enabled
* @author ricky barrette
@@ -176,129 +178,127 @@ public class SkyHook implements GeoPointLocationListener{
public boolean 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
* with the given LocationListener. Following this call, updates will no longer
* occur for this listener.
* called from our skyhook to android fall back class
* (non-Javadoc)
* @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
* @author ricky barrette
*/
public void removeUpdates() {
Log.d(TAG,"removeUpdates()");
mHandler.removeCallbacks(mFallBack);
mListener = null;
isPeriodicEnabled = false;
if(mXps != null)
mXps.abort();
if(mSkyHookFallback != null) {
Log.d(TAG,"disabling fallback");
mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null;
isEnabled = false;
}
isFirstFix = true;
}
/**
*/
public void removeUpdates() {
Log.d(TAG,"removeUpdates()");
mHandler.removeCallbacks(mFallBack);
mListener = null;
isPeriodicEnabled = false;
if(mXps != null)
mXps.abort();
if(mSkyHookFallback != null) {
Log.d(TAG,"disabling fallback");
mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null;
isEnabled = false;
}
isFirstFix = true;
}
/**
* Used for receiving notifications from SkyHook when
* the location has changed. These methods are called if the
* LocationListener has been registered with the location manager service using the method.
* @param listener
* @author ricky barrette
*/
public void setLocationListener(GeoPointLocationListener listener){
public void setLocationListener(final GeoPointLocationListener listener){
Log.d(TAG,"setLocationListener()");
if (mListener == null) {
if (mListener == null)
mListener = listener;
}
}
private void setUIHandler() {
mHandler = new Handler() {
private void setUIHandler() {
mHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case LOCATION_MESSAGE:
if (msg.obj instanceof WPSLocation) {
WPSLocation location = (WPSLocation) msg.obj;
if (mListener != null && location != null) {
if(Debug.DEBUG)
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.onFirstFix(isFirstFix);
hasLocation = true;
isFirstFix = false;
}
public void handleMessage(final Message msg) {
switch (msg.what) {
case LOCATION_MESSAGE:
if (msg.obj instanceof WPSLocation) {
final WPSLocation location = (WPSLocation) msg.obj;
if (mListener != null && location != null) {
if(Debug.DEBUG)
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.onFirstFix(isFirstFix);
hasLocation = true;
isFirstFix = false;
}
}
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;
}
}
};
}
/**
* called from our skyhook to android fall back class
* (non-Javadoc)
* @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint, int)
* @author ricky barrette
*/
@Override
public void onLocationChanged(GeoPoint point, int accuracy) {
if(! hasLocation)
if(mListener != null)
mListener.onLocationChanged(point, accuracy);
}
case ERROR_MESSAGE:
if( msg.obj instanceof WPSReturnCode) {
final WPSReturnCode code = (WPSReturnCode) msg.obj;
if ( code != null)
Log.w(TAG, code.toString());
hasLocation = false;
@Override
public void onFirstFix(boolean firstFix) {
if(mListener != null)
mListener.onFirstFix(firstFix);
/*
* 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");
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
*/
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 Context mContext;
public SkyHookRegistration(Context context){
public SkyHookRegistration(final Context context){
mContext = context;
mXps = new XPS(context);
}
@@ -32,7 +57,7 @@ public class SkyHookRegistration{
/**
* 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
* @author ricky barrette
*/
@@ -41,40 +66,14 @@ public class SkyHookRegistration{
final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null");
String newUser = tm.getLine1Number();
final String newUser = tm.getLine1Number();
if(Debug.DEBUG)
Log.v(SkyHook.TAG, "newUser = " + newUser);
if(newUser == null) {
if(newUser == null)
Log.e(SkyHook.TAG,"users number is null");
}
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
*/
public class SkyHookService extends Service implements GeoPointLocationListener, RegistrationCallback{
public static final String TAG = "SkyHookService";
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
* @param context
@@ -187,7 +49,6 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
public static Intent getStartServiceIntent(final Context context){
return new Intent(context, SkyHookService.class);
}
/**
* a convince method for stopping the service and removing its que from the alarm manager
* @param context
@@ -199,34 +60,72 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
@Override
public void run(){
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
public void onLocationChanged(GeoPoint point, int accuracy) {
this.mLocation = point;
this.mAccuracy = accuracy;
/*
* fail safe
* if the accuracy is greater than the minimum required accuracy
* then continue
* else stop to report location
*/
if(accuracy < (this.mRequiredAccuracy > -1 ? this.mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION)
this.stopSelf(this.mStartID);
private Intent mIntent;
private int mAccuracy;
/**
* broadcasts location to anything listening for updates
*
* @author ricky barrette
*/
private void braodcastLocation() {
if (mLocation != null) {
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
public void done() {
// 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
public WPSContinuation handleError(WPSReturnCode arg0) {
public WPSContinuation handleError(final WPSReturnCode arg0) {
// unused
return null;
}
@@ -234,12 +133,113 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
@Override
public void handleSuccess() {
// 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
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
}
@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;
import com.TwentyCodes.android.location.BaseLocationReceiver;
import android.app.AlarmManager;
import android.hardware.SensorManager;
import android.location.LocationManager;
@@ -17,10 +15,10 @@ import android.location.LocationManager;
* @author ricky barrette
*/
public final class LocationLibraryConstants {
static{
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;
}
@@ -41,37 +39,37 @@ public final class LocationLibraryConstants {
* @author ricky barrette
*/
public static final long MAX_LOCATION_SERVICE_RUN_TIME = 60000l;
/**
* Forces single shot location services to return the first location
* @author ricky barrette
*/
public static final boolean REPORT_FIRST_LOCATION = false;
/**
* Minimum Required accuracy to report
* @author ricky barrette
*/
public static final int MINIMUM_REQUIRED_ACCURACY = 100;
public static final boolean SUPPORTS_FROYO;
public static final boolean SUPPORTS_GINGERBREAD;
public static final String INTENT_ACTION_UPDATE = "TwentyCodes.intent.action.LocationUpdate";
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
*/
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
*/
public static final String INTENT_EXTRA_REQUIRED_ACCURACY = "required_accuracy";
/**
* 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
*/
NORMAL,
NORMAL,
/**
* 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
*/
RETURN_NULL;
}

View File

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

View File

@@ -17,20 +17,29 @@ import com.TwentyCodes.android.location.R;
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
*/
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 DirectionsOverlay mDirections;
/**
* Creates a new DirectionsAdapter
* @author ricky barrette
*/
public DirectionsAdapter(Context context, DirectionsOverlay directions) {
public DirectionsAdapter(final Context context, final DirectionsOverlay directions) {
mInflater = LayoutInflater.from(context);
mDirections = directions;
}
@@ -54,7 +63,7 @@ public class DirectionsAdapter extends BaseAdapter {
* @author ricky barrette
*/
@Override
public Object getItem(int position) {
public Object getItem(final int position) {
return position;
}
@@ -66,7 +75,7 @@ public class DirectionsAdapter extends BaseAdapter {
* @author ricky barrette
*/
@Override
public long getItemId(int position) {
public long getItemId(final int position) {
return position;
}
@@ -82,37 +91,27 @@ public class DirectionsAdapter extends BaseAdapter {
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
/**
* Display the copyrights on the bottom of the directions list
*/
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;
}
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
/**
* this class will hold the TextViews
* @author ricky barrette
*/
class ViewHolder {
TextView text;
TextView text2;
/**
* Display the copyrights on the bottom of the directions list
*/
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;
}
}

View File

@@ -17,18 +17,18 @@ import com.TwentyCodes.android.overlays.DirectionsOverlay;
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
* @author ricky barrette
*/
public class DirectionsListFragment extends ListFragment {
/**
* A simple interfrace for a directions list fragment
* @author ricky barrette
*/
public interface OnDirectionSelectedListener {
/**
* Called when the user selects a direction from a directions list
* @param point
@@ -37,7 +37,7 @@ public class DirectionsListFragment extends ListFragment {
public void onDirectionSelected(GeoPoint point);
}
private OnDirectionSelectedListener mListener;
private ArrayList<GeoPoint> mPoints;
@@ -54,17 +54,17 @@ public class DirectionsListFragment extends ListFragment {
* @param listener
* @author ricky barrette
*/
public DirectionsListFragment(OnDirectionSelectedListener listener) {
public DirectionsListFragment(final OnDirectionSelectedListener listener) {
this();
mListener = listener;
}
/**
* Deletes all content in the listview
* @author ricky barrette
*/
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)
*/
@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(mListener != null)
mListener.onDirectionSelected(mPoints.get(position));
}
/**
* (non-Javadoc)
* @see android.support.v4.app.Fragment#onStart()
*/
@Override
public void onStart() {
this.setListShown(true);
setListShown(true);
super.onStart();
}
@@ -97,7 +97,7 @@ public class DirectionsListFragment extends ListFragment {
*/
public void setDirections(final DirectionsOverlay directions) {
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
* @author ricky barrette
*/
public void SetEmptyText(String text){
this.setEmptyText(text);
public void SetEmptyText(final String text){
setEmptyText(text);
}
}

View File

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

View File

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

View File

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

View File

@@ -16,25 +16,25 @@ import android.location.LocationManager;
* @author ricky barrette
*/
public abstract class BaseLocationReceiver extends BroadcastReceiver {
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
* @param parcelableExtra
* @author ricky barrette
*/
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
*/
public class CompassSensor{
/**
* A simple listener interface to get updates from CompassSensor
* @author ricky barrette
*/
public interface CompassListener {
/**
* Called when there is an update from the Compass Sensor
* @param bearing
@@ -42,7 +42,7 @@ public class CompassSensor{
*/
public void onCompassUpdate(float bearing);
}
public static final String TAG = "CompassSensor";
private static final int BEARING = 0;
private final Display mDisplay;
@@ -55,7 +55,7 @@ public class CompassSensor{
static{
mHandler = new Handler(){
@Override
public void handleMessage(Message msg){
public void handleMessage(final Message msg){
if(mListener != null)
if(msg.what == BEARING)
mListener.onCompassUpdate((Float) msg.obj);
@@ -65,20 +65,25 @@ public class CompassSensor{
private final SensorEventListener mCallBack = new SensorEventListener() {
private float[] mRotationMatrix = new float[16];
// private float[] mRemapedRotationMatrix = new float[16];
private float[] mI = new float[16];
private final float[] mRotationMatrix = new float[16];
// private float[] mRemapedRotationMatrix = new float[16];
private final float[] mI = new float[16];
private float[] mGravity = 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;
// double mPitch = 0;
// double mRoll = 0;
// private float mInclination;
// double mPitch = 0;
// double mRoll = 0;
// private float mInclination;
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
}
@Override
public void onSensorChanged(final SensorEvent sensorEvent) {
if(Debug.DEBUG){
if(Debug.DEBUG)
switch (sensorEvent.accuracy){
case SensorManager.SENSOR_STATUS_UNRELIABLE:
Log.v(TAG , "UNRELIABLE");
@@ -92,91 +97,86 @@ public class CompassSensor{
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
Log.v(TAG , "HIGH");
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
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));
mHandler.sendMessage(mHandler.obtainMessage(BEARING, (float) mAzimuth));
}
};
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
/**
* Creates a new CompassSensor
* @author ricky barrette
@@ -186,7 +186,7 @@ public class CompassSensor{
mDisplay = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
}
/**
* Disables compass updates
* @author ricky barrette
@@ -201,7 +201,7 @@ public class CompassSensor{
* @param listener
* @author ricky barrette
*/
public void enable(CompassListener listener){
public void enable(final CompassListener listener){
if(mListener == null) {
mListener = listener;
if(mSensorManager != null)
@@ -216,21 +216,20 @@ public class CompassSensor{
}).start();
}
}
/**
* Updates the Geomagnetic Field Declination based off of the provided location
* @param location last known (lat,lon,altitude), null will reset
* @author ricky barrette
*/
public void setDeclination(final Location location){
if (location != null) {
final GeomagneticField geomagneticField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis());
mDelination = geomagneticField.getDeclination();
} else {
mDelination = 0;
}
if (location != null) {
final GeomagneticField geomagneticField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis());
mDelination = geomagneticField.getDeclination();
} else
mDelination = 0;
}
}

View File

@@ -12,7 +12,14 @@ import com.google.android.maps.GeoPoint;
* @author ricky barrette
*/
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
* @param point
@@ -20,11 +27,4 @@ public interface GeoPointLocationListener {
* @author ricky barrette
*/
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.
*/
public class GeoUtils {
public static final int EARTH_RADIUS_KM = 6371;
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.
* 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 final double MILLION = 1000000;
/**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East
* @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) {
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) {
if( (user == null) || (dest == null) )
if( user == null || dest == null )
return bearing;
float heading = bearing(user, dest).floatValue();
bearing = (360 - heading) + bearing;
final float heading = bearing(user, dest).floatValue();
bearing = 360 - heading + bearing;
if (bearing > 360)
return bearing - 360;
return bearing;
}
/**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East
* @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
/**
* 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.
*
* @param point central geopoint
* @param point central geopoint
* @param distance in meters from the geopoint
* @return geopoint that is x meters away from the geopoint supplied
* @author ricky barrette
@@ -108,11 +108,11 @@ public class GeoUtils {
public static GeoPoint distanceFrom(final GeoPoint point, double distance){
//convert meters into kilometers
distance = distance / 1000;
// convert lat and lon of geopoint to radians
double lat1Rad = Math.toRadians((point.getLatitudeE6() / 1e6));
double lon1Rad = Math.toRadians((point.getLongitudeE6() / 1e6));
final double lat1Rad = Math.toRadians(point.getLatitudeE6() / 1e6);
final double lon1Rad = Math.toRadians(point.getLongitudeE6() / 1e6);
/*
* 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: 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
*
* 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
*/
double lon2Rad = lon1Rad + Math.acos( Math.cos((distance/6371)) * (1 / Math.cos(lat1Rad))
* (1 / Math.cos(lat1Rad)) - Math.tan(lat1Rad) * Math.tan(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));
//return a geopoint that is x meters away from the geopoint supplied
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
* @param lat1 source lat
* @param lon1 source lon
* @param lat2 destination lat
* @param lon2 destination lon
* @return the distance between to lat1/lon1 and lat2/lon2
* @author Google Inc.
*/
public static double distanceKm(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);
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 lat1/lon1 and lat2/lon2 based on the curve of the earth
* @param lat1 source lat
* @param lon1 source lon
* @param lat2 destination lat
* @param lon2 destination lon
* @return the distance between to lat1/lon1 and lat2/lon2
* @author Google Inc.
*/
public static double distanceKm(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);
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
* @param distance in kilometers
* @param returnMetric true if metric, false for US
@@ -160,8 +179,8 @@ public class GeoUtils {
* @author ricky barrette
*/
public static String distanceToString(double distance, final boolean returnMetric) {
DecimalFormat threeDForm = new DecimalFormat("#.###");
DecimalFormat twoDForm = new DecimalFormat("#.##");
final DecimalFormat threeDForm = new DecimalFormat("#.###");
final DecimalFormat twoDForm = new DecimalFormat("#.##");
if (returnMetric) {
if (distance < 1) {
@@ -177,12 +196,12 @@ public class GeoUtils {
}
return twoDForm.format(distance) + " mi";
}
/**
* 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
/**
* 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
* 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 locationPoint
* @param locationRadius in KM
@@ -191,31 +210,12 @@ public class GeoUtils {
* @author ricky barrette
*/
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 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
* @param point
* @return true is the point is off the map
@@ -226,58 +226,57 @@ public class GeoUtils {
return false;
if (point == null)
return false;
GeoPoint center = map.getMapCenter();
double distance = GeoUtils.distanceKm(center, point);
double distanceLat = GeoUtils.distanceKm(center, new GeoPoint((center.getLatitudeE6() + (int) (map.getLatitudeSpan() / 2)), center.getLongitudeE6()));
double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), (center.getLongitudeE6() + (int) (map.getLongitudeSpan() / 2))));
if (distance > distanceLat || distance > distanceLon){
return true;
}
final GeoPoint center = map.getMapCenter();
final double distance = GeoUtils.distanceKm(center, point);
final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + map.getLatitudeSpan() / 2, center.getLongitudeE6()));
final double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), center.getLongitudeE6() + map.getLongitudeSpan() / 2));
if (distance > distanceLat || distance > distanceLon)
return true;
return false;
}
/**
* computes a geopoint the is the central geopoint between p1 and p1
* @param p1 first geopoint
* @param p2 second geopoint
* @return a MidPoint object
* @author ricky barrette
*/
public static MidPoint midPoint(final GeoPoint p1, final GeoPoint p2) {
int minLatitude = (int)(+81 * 1E6);
int maxLatitude = (int)(-81 * 1E6);
int minLongitude = (int)(+181 * 1E6);
int maxLongitude = (int)(-181 * 1E6);
List<Point> mPoints = new ArrayList<Point>();
int latitude = p1.getLatitudeE6();
int longitude = p1.getLongitudeE6();
if (latitude != 0 && longitude !=0) {
minLatitude = (minLatitude > latitude) ? latitude : minLatitude;
maxLatitude = (maxLatitude < latitude) ? latitude : maxLatitude;
minLongitude = (minLongitude > longitude) ? longitude : minLongitude;
maxLongitude = (maxLongitude < longitude) ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude));
}
latitude = p2.getLatitudeE6();
longitude = p2.getLongitudeE6();
if (latitude != 0 && longitude !=0) {
minLatitude = (minLatitude > latitude) ? latitude : minLatitude;
maxLatitude = (maxLatitude < latitude) ? latitude : maxLatitude;
minLongitude = (minLongitude > longitude) ? longitude : minLongitude;
maxLongitude = (maxLongitude < longitude) ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude));
}
return new MidPoint(new GeoPoint((maxLatitude + minLatitude)/2, (maxLongitude + minLongitude)/2 ), minLatitude, minLongitude, maxLatitude, maxLongitude);
}
/**
* converts radians to bearing
* @param rad
* @return bearing
* @author Google Inc.
*/
public static double radToBearing(final double rad) {
return (Math.toDegrees(rad) + 360) % 360;
}
/**
* computes a geopoint the is the central geopoint between p1 and p1
* @param p1 first geopoint
* @param p2 second geopoint
* @return a MidPoint object
* @author ricky barrette
*/
public static MidPoint midPoint(final GeoPoint p1, final GeoPoint p2) {
int minLatitude = (int)(+81 * 1E6);
int maxLatitude = (int)(-81 * 1E6);
int minLongitude = (int)(+181 * 1E6);
int maxLongitude = (int)(-181 * 1E6);
final List<Point> mPoints = new ArrayList<Point>();
int latitude = p1.getLatitudeE6();
int longitude = p1.getLongitudeE6();
if (latitude != 0 && longitude !=0) {
minLatitude = minLatitude > latitude ? latitude : minLatitude;
maxLatitude = maxLatitude < latitude ? latitude : maxLatitude;
minLongitude = minLongitude > longitude ? longitude : minLongitude;
maxLongitude = maxLongitude < longitude ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude));
}
latitude = p2.getLatitudeE6();
longitude = p2.getLongitudeE6();
if (latitude != 0 && longitude !=0) {
minLatitude = minLatitude > latitude ? latitude : minLatitude;
maxLatitude = maxLatitude < latitude ? latitude : maxLatitude;
minLongitude = minLongitude > longitude ? longitude : minLongitude;
maxLongitude = maxLongitude < longitude ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude));
}
return new MidPoint(new GeoPoint((maxLatitude + minLatitude)/2, (maxLongitude + minLongitude)/2 ), minLatitude, minLongitude, maxLatitude, maxLongitude);
}
/**
* converts radians to bearing
* @param rad
* @return bearing
* @author Google Inc.
*/
public static double radToBearing(final double rad) {
return (Math.toDegrees(rad) + 360) % 360;
}
}

View File

@@ -37,37 +37,53 @@ import com.TwentyCodes.android.debug.LocationLibraryConstants;
* @author ricky barrette
*/
public class LocationService extends Service implements LocationListener {
public static final String TAG = "LocationService";
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 long mPeriod = -1;
private Location mLocation;
private int mStartId;
private AndroidGPS mLocationManager;
private int mRequiredAccuracy;
private Intent mIntent;
/*
* 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
public void run(){
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,
* 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() {
Log.d(TAG, "broadcastLocation()");
if (mLocation != null) {
Intent locationUpdate = new Intent();
final Intent locationUpdate = new Intent();
if(mIntent.getAction() != null)
locationUpdate.setAction(mIntent.getAction());
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
* (non-Javadoc)
@@ -96,19 +125,19 @@ public class LocationService extends Service implements LocationListener {
@Override
public void onCreate(){
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.acquire();
/*
* 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);
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
* (non-Javadoc)
* @see android.app.Service#onDestroy()
@@ -123,119 +152,89 @@ public class LocationService extends Service implements LocationListener {
if(mPeriod > -1)
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
* @author ricky barrette
*/
@Override
public void onStart(Intent intent, int startId) {
public void onStart(final Intent intent, final int startId) {
if(Debug.DEBUG)
Log.i(TAG, "onStart.Service started with start id of: " + startId);
mStartId = startId;
parseIntent(intent);
mLocationManager.enableLocationUpdates(this);
}
/**
* 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) {
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if(Debug.DEBUG)
Log.i(TAG , "onStartCommand.Service started with start id of: " + startId);
mStartId = startId;
parseIntent(intent);
mLocationManager.enableLocationUpdates(this);
mStartId = startId;
parseIntent(intent);
mLocationManager.enableLocationUpdates(this);
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
*
* @author ricky barrette
*/
private void parseIntent(Intent intent){
this.mIntent = intent;
private void parseIntent(final Intent intent){
mIntent = intent;
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);
}
/**
* (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
* @param context
* @return a intent that will start the service
* registers this service to be waken up by android's alarm manager
* @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));
}
};
}
@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
private void registerwakeUp(){
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));
}
}

View File

@@ -5,14 +5,14 @@
*/
package com.TwentyCodes.android.location;
import com.TwentyCodes.android.debug.Debug;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import com.TwentyCodes.android.debug.Debug;
/**
* We use this MapView Because it has double tap zoom capability and exception handling
* @author ricky barrette
@@ -23,21 +23,12 @@ public class MapView extends com.google.android.maps.MapView {
private long mLastTouchTime;
private boolean mDoubleTapZoonEnabled = true;
/**
* @param context
* @param apiKey
* @author ricky barrette
*/
public MapView(Context context, String apiKey) {
super(context, apiKey);
}
/**
* @param context
* @param attrs
* @author ricky barrette
*/
public MapView(Context context, AttributeSet attrs) {
public MapView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@@ -47,57 +38,38 @@ public class MapView extends com.google.android.maps.MapView {
* @param defStyle
* @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);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
long thisTime = System.currentTimeMillis();
if (this.mDoubleTapZoonEnabled && thisTime - mLastTouchTime < 250) {
// Double tap
this.getController().zoomInFixing((int) ev.getX(), (int) ev.getY());
mLastTouchTime = -1;
} else {
// Too slow
mLastTouchTime = thisTime;
}
}
return super.onInterceptTouchEvent(ev);
/**
* @param context
* @param apiKey
* @author ricky barrette
*/
public MapView(final Context context, final String apiKey) {
super(context, apiKey);
}
/**
* We will override the draw method to help prevent issues
* (non-Javadoc)
* @see android.view.View#draw(android.graphics.Canvas)
* @author ricky barrette
*/
@Override
public void draw(Canvas canvas) {
try {
if(this.getZoomLevel() >= 21) {
this.getController().setZoom(20);
}
super.draw(canvas);
}
catch(Exception ex) {
// getController().setCenter(this.getMapCenter());
// getController().setZoom(this.getZoomLevel() - 2);
if(Debug.DEBUG)
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;
@Override
public void draw(final Canvas canvas) {
try {
if(getZoomLevel() >= 21)
getController().setZoom(20);
super.draw(canvas);
}
catch(final Exception ex) {
// getController().setCenter(this.getMapCenter());
// getController().setZoom(this.getZoomLevel() - 2);
if(Debug.DEBUG)
Log.d(TAG, "Internal error in MapView:" + Log.getStackTraceString(ex));
}
}
/**
@@ -107,4 +79,30 @@ public class MapView extends com.google.android.maps.MapView {
public boolean getDoubleTapZoonEnabled() {
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;
/**
* 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
*/
public class MidPoint {
private final int mMinLatitude;
private final int mMaxLatitude;
private final int mMinLongitude;
@@ -23,23 +23,14 @@ public class MidPoint {
* Creates a new MidPoint
* @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;
mMaxLatitude = maxLatitude;
mMinLongitude = minLongitude;
mMaxLongitude = maxLongitude;
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
* @return
@@ -48,4 +39,13 @@ public class MidPoint {
public GeoPoint getMidPoint(){
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){
if (LocationLibraryConstants.SUPPORTS_FROYO) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final PendingIntent locationListenerPassivePendingIntent = PendingIntent.getBroadcast(context, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListenerPassivePendingIntent);
}
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final PendingIntent locationListenerPassivePendingIntent = PendingIntent.getBroadcast(context, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListenerPassivePendingIntent);
}
}
}

View File

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

View File

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

View File

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

View File

@@ -30,14 +30,14 @@ import com.google.android.maps.GeoPoint;
* @author ricky barrette
*/
public class DirectionsOverlay {
/**
* @author ricky barrette
*/
public interface OnDirectionsCompleteListener{
public void onDirectionsComplete(DirectionsOverlay directionsOverlay);
}
private static final String TAG = "DirectionsOverlay";
private ArrayList<PathOverlay> mPath;
private ArrayList<String> mDirections;
@@ -48,24 +48,24 @@ public class DirectionsOverlay {
private ArrayList<String> mDistance;
private ArrayList<String> mDuration;
private ArrayList<String> mWarnings;
/**
* Downloads and Creates a new DirectionsOverlay from the provided points
* @param origin point
* @param destination point
* @author ricky barrette
* @throws IOException
* @throws ClientProtocolException
* @throws IllegalStateException
* @throws JSONException
* @throws IOException
* @throws ClientProtocolException
* @throws IllegalStateException
* @throws JSONException
*/
public DirectionsOverlay(final MapView map, final GeoPoint origin, final GeoPoint destination, final OnDirectionsCompleteListener listener) throws IllegalStateException, ClientProtocolException, IOException, JSONException {
mMapView = map;
mListener = listener;
String json = downloadJSON(generateUrl(origin, destination));
final String json = downloadJSON(generateUrl(origin, destination));
drawPath(json);
}
/**
* Creates a new DirectionsOverlay from the provided String JSON
* @param json
@@ -77,65 +77,66 @@ public class DirectionsOverlay {
mMapView = map;
drawPath(json);
}
/**
* Deocodes googles polyline
* @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 ricky barrette
* @throws JSONException
* @throws JSONException
*/
private void decodePoly(final JSONObject step) throws JSONException {
if(Debug.DEBUG)
Log.d(TAG, "decodePoly");
String encoded = step.getJSONObject("polyline").getString("points");
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
final String encoded = step.getJSONObject("polyline").getString("points");
int index = 0;
final int len = encoded.length();
int lat = 0, lng = 0;
GeoPoint last = null;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
GeoPoint last = null;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
final int dlat = (result & 1) != 0 ? ~(result >> 1) : result >> 1;
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
final int dlng = (result & 1) != 0 ? ~(result >> 1) : result >> 1;
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6), (int) (((double) lng / 1E5) * 1E6));
if(Debug.DEBUG){
final GeoPoint p = new GeoPoint((int) (lat / 1E5 * 1E6), (int) (lng / 1E5 * 1E6));
if(Debug.DEBUG){
Log.d(TAG, "current = "+ p.toString());
if(last != null)
Log.d(TAG, "last = "+ last.toString());
}
if(last != null)
mPath.add(new PathOverlay(last, p, Color.RED));
// else
// mPath.add(new PathOverlay(p, 5, Color.GREEN));
last = p;
}
}
if(last != null)
mPath.add(new PathOverlay(last, p, Color.RED));
// else
// mPath.add(new PathOverlay(p, 5, Color.GREEN));
last = p;
}
}
/**
* Downloads Google Directions JSON from the Internet
* Downloads Google Directions JSON from the Internet
* @param url
* @return
* @throws IllegalStateException
@@ -148,21 +149,21 @@ public class DirectionsOverlay {
Log.d(TAG, url);
if(url == null)
throw new NullPointerException();
StringBuffer response = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent()));
final StringBuffer response = new StringBuffer();
final BufferedReader br = new BufferedReader(new InputStreamReader(new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent()));
String buff = null;
while ((buff = br.readLine()) != null)
response.append(buff);
return response.toString();
}
/**
* Creates a new DirectionsOverlay from the json provided
* @param json of Google Directions API
* @author ricky barrette
* @return
* @throws JSONException
* @return
* @throws JSONException
*/
public void drawPath(final String json) throws JSONException{
if(Debug.DEBUG){
@@ -174,75 +175,75 @@ public class DirectionsOverlay {
mPoints = new ArrayList<GeoPoint>();
mDistance = new ArrayList<String>();
mDuration = new ArrayList<String>();
//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");
//route.getString("status");
JSONObject leg = route.getJSONArray("legs").getJSONObject(0);
final JSONObject leg = route.getJSONArray("legs").getJSONObject(0);
getDistance(leg);
getDuration(leg);
// 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("start_location")), 12, Color.GREEN));
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("end_location")), 12, Color.RED));
leg.getString("start_address");
leg.getString("end_address");
// JSONArray warnings = leg.getJSONArray("warnings");
// for(int i = 0; i < warnings.length(); i++){
// mWarnings.add(warnings.get)w
// }w
// JSONArray warnings = leg.getJSONArray("warnings");
// for(int i = 0; i < warnings.length(); i++){
// mWarnings.add(warnings.get)w
// }w
/*
* here we will parse the steps of the directions
*/
if(Debug.DEBUG)
Log.d(TAG, "processing steps");
JSONArray steps = leg.getJSONArray("steps");
final JSONArray steps = leg.getJSONArray("steps");
JSONObject step = null;
for(int i = 0; i < steps.length(); i++){
if(Debug.DEBUG)
Log.d(TAG, "step "+i);
step = steps.getJSONObject(i);
if(Debug.DEBUG){
Log.d(TAG, "start "+getGeoPoint(step.getJSONObject("start_location")).toString());
Log.d(TAG, "end "+getGeoPoint(step.getJSONObject("end_location")).toString());
}
// if(Debug.DEBUG)
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(step.getJSONObject("start_location")), getGeoPoint(step.getJSONObject("end_location")), Color.MAGENTA));
// if(Debug.DEBUG)
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(step.getJSONObject("start_location")), getGeoPoint(step.getJSONObject("end_location")), Color.MAGENTA));
decodePoly(step);
mDuration.add(getDuration(step));
mDistance.add(getDistance(step));
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")));
}
if(Debug.DEBUG)
Log.d(TAG, "finished parsing");
if(mMapView != null){
mMapView.getOverlays().addAll(mPath);
mMapView.postInvalidate();
}
if(mListener != null)
mListener.onDirectionsComplete(DirectionsOverlay.this);
}
/**
* @param origin
* @param destination
* @return The Google API url for our directions
* @return The Google API url for our directions
* @author ricky barrette
*/
private String generateUrl(final GeoPoint origin, final GeoPoint destination){
@@ -256,7 +257,7 @@ public class DirectionsOverlay {
Double.toString(destination.getLongitudeE6() / 1.0E6)+
"&sensor=true&mode=walking";
}
/**
* @return
* @author ricky barrette
@@ -264,7 +265,7 @@ public class DirectionsOverlay {
public String getCopyrights(){
return mCopyRights;
}
/**
* @return
* @author ricky barrette
@@ -282,7 +283,7 @@ public class DirectionsOverlay {
private String getDistance(final JSONObject step) throws JSONException{
return step.getJSONObject("distance").getString("text");
}
/**
* @return
* @author ricky barrette
@@ -293,7 +294,7 @@ public class DirectionsOverlay {
/**
* @param step
* @return the duration of a step
* @return the duration of a step
* @throws JSONException
* @author ricky barrette
*/
@@ -327,7 +328,7 @@ public class DirectionsOverlay {
public ArrayList<PathOverlay> getPath(){
return mPath;
}
/**
* @return
* @author ricky barrette
@@ -349,6 +350,6 @@ public class DirectionsOverlay {
* @author ricky barrette
*/
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;
mRadius = 0;
}
/**
* Creates a new PathOverlay in point mode. This is used to draw end points.
* @param point
@@ -56,29 +56,29 @@ public final class PathOverlay extends Overlay {
mEnd = mStart;
mColor = color;
}
/**
*
* @param canvas canvas to be drawn on
* @param mapView
* @param shadow
* @param mapView
* @param shadow
* @param when
*/
@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 Paint paint = new Paint();
paint.setColor(mColor);
paint.setAntiAlias(true);
Point point = new Point();
final Point point = new Point();
projection.toPixels(mStart, point);
switch (mMode){
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);
case PATH:
Point point2 = new Point();
final Point point2 = new Point();
projection.toPixels(mEnd, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
@@ -86,20 +86,20 @@ public final class PathOverlay extends Overlay {
}
super.draw(canvas, mapView, shadow);
}
/**
* @return the end point of this path
* @author ricky barrette
*/
public GeoPoint getEndPoint(){
return this.mEnd;
return mEnd;
}
/**
* @return the start point of this path
* @author ricky barrette
*/
public GeoPoint getStartPoint(){
return this.mStart;
return mStart;
}
}

View File

@@ -1,7 +1,7 @@
/**
* @author Twenty Codes
* @author ricky barrette
*/
* @author Twenty Codes
* @author ricky barrette
*/
package com.TwentyCodes.android.overlays;
@@ -21,7 +21,7 @@ import com.google.android.maps.OverlayItem;
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
* @author ricky barrette
*/
@@ -33,32 +33,32 @@ public class RadiusOverlay extends Overlay{
private int mColor = Color.GREEN;
private GeoPoint mRadiusPoint;
private OnLocationSelectedListener mListener;
/**
* Creates a new RadiusOverlay
* @author ricky barrette
*/
public RadiusOverlay(){
}
/**
* 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 color desired color of the radius from Color API
* @author ricky barrette
*/
public RadiusOverlay(GeoPoint point, float radius, int color) {
public RadiusOverlay(final GeoPoint point, final float radius, final int color) {
mPoint = point;
mRadius = radius;
mColor = color;
}
/**
* draws a specific radius on the mapview that is handed to it
* @param canvas canvas to be drawn on
* @param mapView
* @param shadow
* @param mapView
* @param shadow
* @param when
*/
@Override
@@ -68,44 +68,43 @@ public class RadiusOverlay extends Overlay{
final Point center = new Point();
final Point left = new Point();
final Projection projection = mapView.getProjection();
/*
* Calculate a geopoint that is "radius" meters away from geopoint point and
* convert the given GeoPoint and leftGeo to onscreen pixel coordinates,
* relative to the top-left of the MapView that provided this Projection.
*/
mRadiusPoint = GeoUtils.distanceFrom(mPoint , mRadius);
projection.toPixels(mRadiusPoint, left);
projection.toPixels(mPoint, center);
/*
* get radius of the circle being drawn by
*/
int circleRadius = center.x - left.x;
if(circleRadius <= 0){
circleRadius = left.x - center.x;
}
/*
* paint a circle on the map
*/
paint.setAntiAlias(true);
paint.setStrokeWidth(2.0f);
paint.setColor(mColor);
paint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, circleRadius, paint);
//draw a dot over the geopoint
RectF oval = new RectF(center.x - 2, center.y - 2, center.x + 2, center.y + 2);
/*
* Calculate a geopoint that is "radius" meters away from geopoint point and
* convert the given GeoPoint and leftGeo to onscreen pixel coordinates,
* relative to the top-left of the MapView that provided this Projection.
*/
mRadiusPoint = GeoUtils.distanceFrom(mPoint , mRadius);
projection.toPixels(mRadiusPoint, left);
projection.toPixels(mPoint, center);
/*
* get radius of the circle being drawn by
*/
int circleRadius = center.x - left.x;
if(circleRadius <= 0)
circleRadius = left.x - center.x;
/*
* paint a circle on the map
*/
paint.setAntiAlias(true);
paint.setStrokeWidth(2.0f);
paint.setColor(mColor);
paint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, circleRadius, paint);
//draw a dot over the geopoint
final RectF oval = new RectF(center.x - 2, center.y - 2, center.x + 2, center.y + 2);
canvas.drawOval(oval, paint);
//fill the radius with a nice green
paint.setAlpha(25);
paint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, circleRadius, paint);
paint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, circleRadius, paint);
}
}
/**
* @return the selected location
* @author ricky barrette
@@ -113,12 +112,17 @@ public class RadiusOverlay extends Overlay{
public GeoPoint getLocation(){
return mPoint;
}
public int getZoomLevel() {
// GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius)
return 0;
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
public boolean onTap(final GeoPoint p, final MapView mapView) {
mPoint = p;
if(this.mListener != null)
this.mListener.onLocationSelected(p);
if(mListener != null)
mListener.onLocationSelected(p);
return super.onTap(p, mapView);
}
@@ -126,33 +130,28 @@ public class RadiusOverlay extends Overlay{
* @param color
* @author ricky barrette
*/
public void setColor(int color){
public void setColor(final int color){
mColor = color;
}
/**
* @param location
* @author ricky barrette
*/
public void setLocation(GeoPoint location){
public void setLocation(final GeoPoint location){
mPoint = location;
}
public void setLocationSelectedListener(final OnLocationSelectedListener listener) {
mListener = listener;
}
/**
* @param radius in meters
* @author ricky barrette
* @param radius
* @param radius
*/
public void setRadius(int radius){
public void setRadius(final int 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{
private final SkyHook mSkyHook;
public SkyHookUserOverlay(MapView mapView, Context context) {
public SkyHookUserOverlay(final MapView mapView, final Context context) {
super(mapView, context);
mSkyHook = new SkyHook(context);
}
/**
* Construct a new SkyHookUserOverlay
* @param mapView
@@ -30,11 +30,16 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
* @param followUser
* @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);
mSkyHook = new SkyHook(context);
}
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
/**
* Called when the location provider needs to be disabled
* (non-Javadoc)
@@ -56,9 +61,4 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
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;
/**
* This is the standard version of the UserOverlay.
* This is the standard version of the UserOverlay.
* @author ricky barrette
*/
public class UserOverlay extends BaseUserOverlay{
private final AndroidGPS mAndroidGPS;
public UserOverlay(MapView mapView, Context context) {
public UserOverlay(final MapView mapView, final Context context) {
super(mapView, 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);
mAndroidGPS = new AndroidGPS(context);
}
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
@Override
public void onMyLocationDisabled() {
mAndroidGPS.disableLocationUpdates();
@@ -38,9 +43,4 @@ public class UserOverlay extends BaseUserOverlay{
mAndroidGPS.enableLocationUpdates(this);
}
@Override
public void onFirstFix(boolean isFistFix) {
// unused
}
}