Commit a85d5b90 authored by Chris Scott's avatar Chris Scott

Implement getCurrentPosition method

parent cb5d84e0
...@@ -20,6 +20,8 @@ The plugin creates the object `window.plugins.backgroundGeoLocation` with the me ...@@ -20,6 +20,8 @@ The plugin creates the object `window.plugins.backgroundGeoLocation` with the me
`changePace(true) // engages aggressive monitoring immediately` `changePace(true) // engages aggressive monitoring immediately`
`getCurrentPosition(success, fail)`
`onMotionChange(callback, fail)` `onMotionChange(callback, fail)`
`addGeofence(config, callback, fail)` `addGeofence(config, callback, fail)`
...@@ -273,6 +275,17 @@ Disable background geolocation tracking. ...@@ -273,6 +275,17 @@ Disable background geolocation tracking.
bgGeo.stop(); bgGeo.stop();
``` ```
####`getCurrentPosition(successFn, failureFn)`
Retrieves the current position. This method instructs the native code to fetch exactly one location using maximum power & accuracy. The native code will persist the fetched location to SQLite just as any other location in addition to POSTing to your configured `#url` (if you've enabled the HTTP features). In addition to your supplied `callbackFn`, the plugin will also execute the `callback` provided to `#configure`. Your provided `successFn` will be executed with the same signature as that provided to `#configure`:
######@param {Object} location The Location data
######@param {Integer} taskId The taskId used to send to bgGeo.finish(taskId) in order to signal completion of your callbackFn
```
bgGeo.changePace(true); // <-- Aggressive GPS monitoring immediately engaged.
bgGeo.changePace(false); // <-- Disable aggressive GPS monitoring. Engages stationary-mode.
```
####`changePace(enabled, successFn, failureFn)` ####`changePace(enabled, successFn, failureFn)`
Initiate or cancel immediate background tracking. When set to ```true```, the plugin will begin aggressively tracking the devices Geolocation, bypassing stationary monitoring. If you were making a "Jogging" application, this would be your [Start Workout] button to immediately begin GPS tracking. Send ```false``` to disable aggressive GPS monitoring and return to stationary-monitoring mode. Initiate or cancel immediate background tracking. When set to ```true```, the plugin will begin aggressively tracking the devices Geolocation, bypassing stationary monitoring. If you were making a "Jogging" application, this would be your [Start Workout] button to immediately begin GPS tracking. Send ```false``` to disable aggressive GPS monitoring and return to stationary-monitoring mode.
......
...@@ -56,7 +56,7 @@ public class CDVBackgroundGeolocation extends CordovaPlugin { ...@@ -56,7 +56,7 @@ public class CDVBackgroundGeolocation extends CordovaPlugin {
private Boolean isEnabled = false; private Boolean isEnabled = false;
private Boolean stopOnTerminate = false; private Boolean stopOnTerminate = false;
private Boolean isMoving = false; private Boolean isMoving = false;
private Boolean isAcquiringCurrentPosition = false;
private Intent backgroundServiceIntent; private Intent backgroundServiceIntent;
private DetectedActivity currentActivity; private DetectedActivity currentActivity;
...@@ -75,6 +75,7 @@ public class CDVBackgroundGeolocation extends CordovaPlugin { ...@@ -75,6 +75,7 @@ public class CDVBackgroundGeolocation extends CordovaPlugin {
private List<CallbackContext> motionChangeCallbacks = new ArrayList<CallbackContext>(); private List<CallbackContext> motionChangeCallbacks = new ArrayList<CallbackContext>();
private List<CallbackContext> geofenceCallbacks = new ArrayList<CallbackContext>(); private List<CallbackContext> geofenceCallbacks = new ArrayList<CallbackContext>();
private List<CallbackContext> currentPositionCallbacks = new ArrayList<CallbackContext>();
public static boolean isActive() { public static boolean isActive() {
return gWebView != null; return gWebView != null;
...@@ -205,10 +206,22 @@ public class CDVBackgroundGeolocation extends CordovaPlugin { ...@@ -205,10 +206,22 @@ public class CDVBackgroundGeolocation extends CordovaPlugin {
result = true; result = true;
playSound(data.getInt(0)); playSound(data.getInt(0));
callbackContext.success(); callbackContext.success();
} else if (BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION.equalsIgnoreCase(action)) {
result = true;
onGetCurrentPosition(callbackContext);
} }
return result; return result;
} }
private void onGetCurrentPosition(CallbackContext callbackContext) {
isAcquiringCurrentPosition = true;
addCurrentPositionListener(callbackContext);
Bundle event = new Bundle();
event.putString("name", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION);
event.putBoolean("request", true);
EventBus.getDefault().post(event);
}
private Boolean onAddGeofence(JSONObject config) { private Boolean onAddGeofence(JSONObject config) {
try { try {
Bundle event = new Bundle(); Bundle event = new Bundle();
...@@ -246,6 +259,9 @@ public class CDVBackgroundGeolocation extends CordovaPlugin { ...@@ -246,6 +259,9 @@ public class CDVBackgroundGeolocation extends CordovaPlugin {
} }
} }
} }
private void addCurrentPositionListener(CallbackContext callbackContext) {
currentPositionCallbacks.add(callbackContext);
}
private void addMotionChangeListener(CallbackContext callbackContext) { private void addMotionChangeListener(CallbackContext callbackContext) {
motionChangeCallbacks.add(callbackContext); motionChangeCallbacks.add(callbackContext);
...@@ -500,18 +516,27 @@ public class CDVBackgroundGeolocation extends CordovaPlugin { ...@@ -500,18 +516,27 @@ public class CDVBackgroundGeolocation extends CordovaPlugin {
* @param {Location} location * @param {Location} location
*/ */
public void onEventMainThread(Location location) { public void onEventMainThread(Location location) {
this.onLocationChange(BackgroundGeolocationService.locationToJson(location, currentActivity)); JSONObject locationData = BackgroundGeolocationService.locationToJson(location, currentActivity);
this.onLocationChange(locationData);
} }
private void onLocationChange(JSONObject location) { private void onLocationChange(JSONObject location) {
PluginResult result; PluginResult result = new PluginResult(PluginResult.Status.OK, location);
result = new PluginResult(PluginResult.Status.OK, location);
result.setKeepCallback(true); result.setKeepCallback(true);
isMoving = true; isMoving = true;
result.setKeepCallback(true); result.setKeepCallback(true);
runInBackground(locationCallback, result); runInBackground(locationCallback, result);
}
if (isAcquiringCurrentPosition) {
isAcquiringCurrentPosition = false;
for (CallbackContext callback : currentPositionCallbacks) {
result = new PluginResult(PluginResult.Status.OK, location);
result.setKeepCallback(false);
runInBackground(callback, result);
}
currentPositionCallbacks.clear();
}
}
/** /**
* EventBus handler for Geofencing events * EventBus handler for Geofencing events
*/ */
......
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
@property (nonatomic, strong) NSString* syncCallbackId; @property (nonatomic, strong) NSString* syncCallbackId;
@property (nonatomic) UIBackgroundTaskIdentifier syncTaskId; @property (nonatomic) UIBackgroundTaskIdentifier syncTaskId;
@property (nonatomic, strong) NSString* locationCallbackId; @property (nonatomic, strong) NSString* locationCallbackId;
@property (nonatomic, strong) NSMutableArray* currentPositionListeners;
@property (nonatomic, strong) NSMutableArray* geofenceListeners; @property (nonatomic, strong) NSMutableArray* geofenceListeners;
@property (nonatomic, strong) NSMutableArray* stationaryRegionListeners; @property (nonatomic, strong) NSMutableArray* stationaryRegionListeners;
@property (nonatomic, strong) NSMutableArray* motionChangeListeners; @property (nonatomic, strong) NSMutableArray* motionChangeListeners;
...@@ -34,6 +35,7 @@ ...@@ -34,6 +35,7 @@
- (void) removeGeofence:(CDVInvokedUrlCommand *)command; - (void) removeGeofence:(CDVInvokedUrlCommand *)command;
- (void) getGeofences:(CDVInvokedUrlCommand *)command; - (void) getGeofences:(CDVInvokedUrlCommand *)command;
- (void) onGeofence:(CDVInvokedUrlCommand *)command; - (void) onGeofence:(CDVInvokedUrlCommand *)command;
- (void) getCurrentPosition:(CDVInvokedUrlCommand *)command;
- (void) playSound:(CDVInvokedUrlCommand *)command; - (void) playSound:(CDVInvokedUrlCommand *)command;
@end @end
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
NSDictionary *config; NSDictionary *config;
} }
@synthesize syncCallbackId, syncTaskId, locationCallbackId, geofenceListeners, stationaryRegionListeners, motionChangeListeners; @synthesize syncCallbackId, syncTaskId, locationCallbackId, geofenceListeners, stationaryRegionListeners, motionChangeListeners, currentPositionListeners;
- (void)pluginInitialize - (void)pluginInitialize
{ {
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMotionChange:) name:@"TSLocationManager.motionchange" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMotionChange:) name:@"TSLocationManager.motionchange" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onEnterGeofence:) name:@"TSLocationManager.geofence" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onEnterGeofence:) name:@"TSLocationManager.geofence" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSyncComplete:) name:@"TSLocationManager.sync" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSyncComplete:) name:@"TSLocationManager.sync" object:nil];
} }
/** /**
...@@ -90,8 +91,9 @@ ...@@ -90,8 +91,9 @@
- (void)onLocationChanged:(NSNotification*)notification { - (void)onLocationChanged:(NSNotification*)notification {
CLLocation *location = [notification.userInfo objectForKey:@"location"]; CLLocation *location = [notification.userInfo objectForKey:@"location"];
NSDictionary *locationData = [bgGeo locationToDictionary:location];
NSDictionary *params = @{ NSDictionary *params = @{
@"location": [bgGeo locationToDictionary:location], @"location": locationData,
@"taskId": @([bgGeo createBackgroundTask]) @"taskId": @([bgGeo createBackgroundTask])
}; };
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:params]; CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:params];
...@@ -100,6 +102,21 @@ ...@@ -100,6 +102,21 @@
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
[self.commandDelegate sendPluginResult:result callbackId:self.locationCallbackId]; [self.commandDelegate sendPluginResult:result callbackId:self.locationCallbackId];
}]; }];
if ([self.currentPositionListeners count]) {
for (NSString *callbackId in self.currentPositionListeners) {
NSDictionary *params = @{
@"location": locationData,
@"taskId": @([bgGeo createBackgroundTask])
};
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:params];
[result setKeepCallbackAsBool:NO];
[self.commandDelegate runInBackground:^{
[self.commandDelegate sendPluginResult:result callbackId:callbackId];
}];
}
[self.currentPositionListeners removeAllObjects];
}
} }
...@@ -299,6 +316,15 @@ ...@@ -299,6 +316,15 @@
[self.geofenceListeners addObject:command.callbackId]; [self.geofenceListeners addObject:command.callbackId];
} }
- (void) getCurrentPosition:(CDVInvokedUrlCommand*)command
{
if (self.currentPositionListeners == nil) {
self.currentPositionListeners = [[NSMutableArray alloc] init];
}
[self.currentPositionListeners addObject:command.callbackId];
[bgGeo updateCurrentPosition];
}
- (void) playSound:(CDVInvokedUrlCommand*)command - (void) playSound:(CDVInvokedUrlCommand*)command
{ {
int soundId = [[command.arguments objectAtIndex:0] integerValue]; int soundId = [[command.arguments objectAtIndex:0] integerValue];
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
- (void) addGeofence:(NSString*)identifier radius:(CLLocationDistance)radius latitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude notifyOnEntry:(BOOL)notifyOnEntry notifyOnExit:(BOOL)notifyOnExit; - (void) addGeofence:(NSString*)identifier radius:(CLLocationDistance)radius latitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude notifyOnEntry:(BOOL)notifyOnEntry notifyOnExit:(BOOL)notifyOnExit;
- (BOOL) removeGeofence:(NSString*)identifier; - (BOOL) removeGeofence:(NSString*)identifier;
- (NSArray*) getGeofences; - (NSArray*) getGeofences;
- (void) updateCurrentPosition;
- (void) playSound:(SystemSoundID)soundId; - (void) playSound:(SystemSoundID)soundId;
@end @end
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<dict> <dict>
<key>Headers/TSLocationManager.h</key> <key>Headers/TSLocationManager.h</key>
<data> <data>
XspAWrxbSpr4Vn4KKi6gq+GKYz4= JKFHIrez0AKQjHebrRIQXFDiIfQ=
</data> </data>
<key>Info.plist</key> <key>Info.plist</key>
<data> <data>
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
<dict> <dict>
<key>Headers/TSLocationManager.h</key> <key>Headers/TSLocationManager.h</key>
<data> <data>
XspAWrxbSpr4Vn4KKi6gq+GKYz4= JKFHIrez0AKQjHebrRIQXFDiIfQ=
</data> </data>
<key>Modules/module.modulemap</key> <key>Modules/module.modulemap</key>
<data> <data>
......
...@@ -293,6 +293,31 @@ module.exports = { ...@@ -293,6 +293,31 @@ module.exports = {
[]); []);
}, },
/** /**
* Fetch the current position
*/
getCurrentPosition: function(success, failure) {
var me = this;
success = success || function(location, taskId) {
me.finish(taskId);
};
var mySuccess = function(params) {
var location = params.location || params;
var taskId = params.taskId || 'task-id-undefined';
// Transform timestamp to Date instance.
if (location.timestamp) {
location.timestamp = new Date(location.timestamp);
}
me._runBackgroundTask(taskId, function() {
success.call(this, location, taskId);
});
}
exec(mySuccess || function() {},
failure || function() {},
'BackgroundGeoLocation',
'getCurrentPosition',
[]);
},
/**
* Play a system sound. This is totally experimental. * Play a system sound. This is totally experimental.
* iOS http://iphonedevwiki.net/index.php/AudioServices * iOS http://iphonedevwiki.net/index.php/AudioServices
* Android: * Android:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment