Skip to content
This repository was archived by the owner on Nov 8, 2023. It is now read-only.

Replaced the Android implementation with the recommended one. #72

Merged
merged 13 commits into from
Oct 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ geolocation.enableLocationRequest();

````
// Get current location with high accuracy
geolocation.getCurrentLocation({ desiredAccuracy: Accuracy.high, updateDistance: 0.1, maximumAge: 5000, timeout: 20000 })
geolocation.getCurrentLocation({ desiredAccuracy: Accuracy.high, maximumAge: 5000, timeout: 20000 })
````

## API
Expand All @@ -69,10 +69,11 @@ geolocation.getCurrentLocation({ desiredAccuracy: Accuracy.high, updateDistance:
| Property | Default | Description |
| --- | --- | --- |
| desiredAccuracy? | Accuracy.high | Specifies desired accuracy in meters. |
| updateDistance | iOS - no filter, Android - 0 meters | Update distance filter in meters. Specifies how often to update the location. |
| minimumUpdateTime | - | Minimum time interval between location updates, in milliseconds (ignored on iOS). |
| updateDistance | iOS - no filter | Update distance filter in meters. Specifies how often to update the location (ignored on Android). |
| updateTime | 1 minute | Interval between location updates, in milliseconds (ignored on iOS). |
| minimumUpdateTime | 5 secs | Minimum time interval between location updates, in milliseconds (ignored on iOS). |
| maximumAge | - | How old locations to receive in ms. |
| timeout | - | How long to wait for a location in ms. |
| timeout | 5 minutes | How long to wait for a location in ms. |

### Methods

Expand All @@ -81,8 +82,8 @@ geolocation.getCurrentLocation({ desiredAccuracy: Accuracy.high, updateDistance:
| getCurrentLocation(options: Options) | Promise<Location> | Get current location applying the specified options (if any). |
| watchLocation(successCallback: successCallbackType, errorCallback: errorCallbackType, options: Options) | number | Monitor for location change. |
| clearWatch(watchId: number) | void | Stop monitoring for location change. Parameter expected is the watchId returned from `watchLocation`. |
| enableLocationRequest(always?: boolean) | Promise<void> | Ask for permissions to use location services. The option `always` is application for iOS only. [Read more about its usage](https://developer.apple.com/documentation/corelocation/cllocationmanager/1620551-requestalwaysauthorization) . |
| isEnabled | boolean| Returns `true` if location services are enabled. |
| enableLocationRequest(always?: boolean) | Promise\<void\> | Ask for permissions to use location services. The option `always` is application for iOS only. [Read more about its usage](https://developer.apple.com/documentation/corelocation/cllocationmanager/1620551-requestalwaysauthorization) . |
| isEnabled | Promise\<boolean\>| Resolves `true` or `false` based on the location services availability. |
| distance(loc1: Location, loc2: Location) | number | Calculate the distance between two locations. Returns the distance in meters. |

## License
Expand Down
Binary file added demo/.cloud/Build.zip
Binary file not shown.
7 changes: 7 additions & 0 deletions demo/app/App_Resources/Android/app.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,10 @@ android {
additionalParameters "--no-version-vectors"
}
}

def settingsGradlePath = "$projectDir/../../app/App_Resources/Android/settings.gradle";
def settingsGradleFile = new File(settingsGradlePath);
if(settingsGradleFile.exists())
{
apply from: settingsGradleFile;
}
44 changes: 44 additions & 0 deletions demo/app/App_Resources/Android/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import groovy.json.JsonSlurper

task replaceSettings {
description "Replaces configuration settings."
def jsonSlurper = new JsonSlurper();
def pathToSettingsJson = "$projectDir/../../app/App_Resources/Android/settings.json";
def settingsJsonFile = file(pathToSettingsJson);
def settingsResolvedPath = settingsJsonFile.getAbsolutePath();

if(settingsJsonFile.exists())
{
println "\t Applying settings from $settingsResolvedPath"
String settingsGradleTemplate = """android {
defaultConfig {
applicationId = "__appId__"

if (__minSdkVersion__) {
minSdkVersion = __minSdkVersion__
}

if (__targetSdkVersion__) {
targetSdkVersion = __targetSdkVersion__
}
}
}"""

def settingsJsonContent = settingsJsonFile.getText("UTF-8");
def settingsMap = jsonSlurper.parseText(settingsJsonContent);

for ( setting in settingsMap ) {
def placeholder = "__${setting.key}__";
def settingValue = setting.value;

if (settingValue == null) {
settingValue = false
}

settingsGradleTemplate = settingsGradleTemplate.replaceAll( placeholder, settingValue as String);
}

new File( './temp_setting.gradle' ).write( settingsGradleTemplate, 'UTF-8');
apply from: './temp_setting.gradle';
}
}
1 change: 1 addition & 0 deletions demo/app/App_Resources/Android/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"appId":"org.nativescript.demo","minSdkVersion":null,"targetSdkVersion":null}
60 changes: 41 additions & 19 deletions demo/app/main-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,68 @@ import { MainViewModel } from "./main-view-model";

let page: Page;
let model = new MainViewModel();
let watchId;
let watchIds = [];

export function pageLoaded(args: EventData) {
page = <Page>args.object;
page.bindingContext = model;
}

export function enableLocationTap() {
if (!geolocation.isEnabled()) {
geolocation.enableLocationRequest();
}
geolocation.isEnabled().then(function (isEnabled) {
if (!isEnabled) {
geolocation.enableLocationRequest().then(function () {
}, function (e) {
console.log("Error: " + (e.message || e));
});
}
}, function (e) {
console.log("Error: " + (e.message || e));
});
}

export function buttonGetLocationTap() {
let location = geolocation.getCurrentLocation({ desiredAccuracy: Accuracy.high, updateDistance: 0.1, maximumAge: 5000, timeout: 20000 })
.then(function(loc) {
let location = geolocation.getCurrentLocation({
desiredAccuracy: Accuracy.high,
maximumAge: 5000,
timeout: 10000
})
.then(function (loc) {
if (loc) {
model.locations.push(loc);
}
}, function(e) {
console.log("Error: " + e.message);
}, function (e) {
console.log("Error: " + (e.message || e));
});
}

export function buttonStartTap() {
watchId = geolocation.watchLocation(
function(loc) {
if (loc) {
model.locations.push(loc);
}
},
function(e) {
console.log("Error: " + e.message);
},
{ desiredAccuracy: Accuracy.high, updateDistance: 0.1, minimumUpdateTime: 100 });
try {
watchIds.push(geolocation.watchLocation(
function (loc) {
if (loc) {
model.locations.push(loc);
}
},
function (e) {
console.log("Error: " + e.message);
},
{
desiredAccuracy: Accuracy.high,
updateDistance: 0.1,
updateTime: 3000,
minimumUpdateTime: 100
}));
} catch (ex) {
console.log("Error: " + ex.message);
}
}

export function buttonStopTap() {
if (watchId) {
let watchId = watchIds.pop();
while (watchId != null) {
geolocation.clearWatch(watchId);
watchId = watchIds.pop();
}
}

Expand Down
94 changes: 42 additions & 52 deletions demo/app/tests/mock-android.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,51 @@ Object.defineProperty(exports, "__esModule", {
value: true
});

var MockLocationManager = (function () {
function MockLocationManager() {
this.MOCK_PROVIDER_NAME = "mockLocationProvider";
}
MockLocationManager.prototype._lastKnownLocation = null;
MockLocationManager.prototype.requestSingleUpdate = function (options, locListener, looper) {
var newLocation = new android.location.Location(this.MOCK_PROVIDER_NAME);
newLocation.setLatitude(this._getRandomCoordinate());
newLocation.setLongitude(this._getRandomCoordinate());
newLocation.setTime((new Date()).getTime());
newLocation.setAccuracy(500);
var geoLocation = require("nativescript-geolocation");
var MockLocationManager = {
};
MockLocationManager.intervalId = null;
MockLocationManager._lastKnownLocation = null;
MockLocationManager._getRandomCoordinate = function () {
var min = -180;
var max = 180;
return Math.floor(Math.random() * (max - min + 1) + min);
};
MockLocationManager.getNewLocation = function () {
var newLocation = new android.location.Location("mockLocationProvider");
var latitude = MockLocationManager._getRandomCoordinate();
var longitude = MockLocationManager._getRandomCoordinate();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
newLocation.setTime((new Date()).getTime());
newLocation.setAccuracy(500);

MockLocationManager.prototype._lastKnownLocation = newLocation;
return newLocation;
};
MockLocationManager.getLastLocation = function (maximumAge, resolve, reject) {
var lastLocation = MockLocationManager._lastKnownLocation ?
new geoLocation.Location(MockLocationManager._lastKnownLocation) : null;

locListener.onLocationChanged(newLocation);
};
MockLocationManager.prototype.getProviders = function (criteria, enabledOnly) {
var providers = [this.MOCK_PROVIDER_NAME];
providers.index = 0;
providers.size = function () {
return providers.length;
};
providers.iterator = function () {
return {
hasNext: function () {
return providers.index < providers.length;
},
next: function () {
var next = providers[providers.index];
providers.index += 1;
return next;
}
};
}
return providers;
};
MockLocationManager.prototype.removeUpdates = function (listener) {
clearInterval(MockLocationManager.intervalId);
};
MockLocationManager.prototype.requestLocationUpdates = function (minTime, minDistance, criteria, listener, looper) {
var _this = this;
this.removeUpdates(null);
resolve(lastLocation);
};
MockLocationManager.removeLocationUpdates = function (listener) {
clearInterval(MockLocationManager.intervalId);
};
MockLocationManager.requestLocationUpdates = function (locationRequest, locationCallback) {
MockLocationManager.removeLocationUpdates(null);
setTimeout(() => {
MockLocationManager.intervalId = setInterval(function () {
return _this.requestSingleUpdate(null, listener, null);
locationCallback.onLocationResult({
getLastLocation: function () {
MockLocationManager._lastKnownLocation = MockLocationManager.getNewLocation();
return MockLocationManager._lastKnownLocation;
}
});
}, 500);
};
MockLocationManager.prototype.getLastKnownLocation = function () {
return MockLocationManager.prototype._lastKnownLocation;
};
MockLocationManager.prototype._getRandomCoordinate = function () {
var min = -180;
var max = 180;
return Math.floor(Math.random() * (max - min + 1) + min);
};
return MockLocationManager;
}());
}, 50);
};
MockLocationManager.shouldSkipChecks = function () {
return true;
}

exports.MockLocationManager = MockLocationManager;
2 changes: 1 addition & 1 deletion demo/app/tests/mock-ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,4 @@ function locationFromCLLocation(clLocation) {
return location;
};

exports.MockLocationManager = MockLocationManager;
exports.MockLocationManager = new MockLocationManager();
40 changes: 29 additions & 11 deletions demo/app/tests/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,34 @@ var MockLocationManager = require(mockLocationManagerPath).MockLocationManager;

describe("location class", function () {
it("can be instantiated", function () {

var geolocation = require("nativescript-geolocation");
var Location = geolocation.Location;
var geoLocation = require("nativescript-geolocation");
var Location = geoLocation.Location;
var nativeLocation = null;
if (MockLocationManager.getNewLocation) {
nativeLocation = MockLocationManager.getNewLocation();
}

expect(function () {
return new Location();
return new Location(nativeLocation);
}).not.toThrow();

expect(new Location()).toBeDefined();
expect(new Location(nativeLocation)).toBeDefined();
});
});

describe("geolocation", function () {
beforeEach(function () {
geolocation = require("nativescript-geolocation");
geolocation.setCustomLocationManager(new MockLocationManager());
geolocation.setCustomLocationManager(MockLocationManager);
});

it("getCurrentLocation returns fresh location when timeout > 0", function (done) {
var location = geolocation.getCurrentLocation({
desiredAccuracy: Accuracy.high,
updateDistance: 0.1,
maximumAge: 5000,
timeout: 20000
})
desiredAccuracy: Accuracy.high,
updateDistance: 0.1,
maximumAge: 5000,
timeout: 20000
})
.then(function (loc) {
expect(loc).toBeDefined();
expect(180 > loc.latitude > -180).toBeTruthy();
Expand All @@ -39,6 +42,21 @@ describe("geolocation", function () {
});
});

it("getCurrentLocation returns timeout when timeout = 20", function (done) {
var location = geolocation.getCurrentLocation({
desiredAccuracy: Accuracy.high,
updateDistance: 0.1,
maximumAge: 5000,
timeout: 20
})
.then(function (loc) {
done.fail("Got location instead of timeout: " + loc);
}, function (e) {
expect(e.message).toEqual('Timeout while searching for location!');
done();
});
});

it("getCurrentLocation returns last known location (if any) when timeout = 0", function (done) {
var getCurrentLocation = function (timeout) {
return geolocation.getCurrentLocation({
Expand Down
6 changes: 4 additions & 2 deletions demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"version": "3.0.1"
},
"tns-android": {
"version": "3.0.0"
"version": "3.2.0"
}
},
"dependencies": {
Expand All @@ -29,9 +29,11 @@
"lazy": "1.0.11",
"nativescript-css-loader": "~0.26.0",
"nativescript-dev-typescript": "libs",
"nativescript-dev-webpack": "^0.7.3",
"nativescript-dev-webpack": "0.8.0",
"nativescript-worker-loader": "~0.8.1",
"raw-loader": "~0.5.1",
"resolve-url-loader": "~2.1.0",
"tns-platform-declarations": "^3.2.0",
"tslint": "~5.4.3",
"typescript": "2.3.4",
"webpack": "~3.2.0",
Expand Down
4 changes: 3 additions & 1 deletion demo/references.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" /> Needed for autocompletion and compilation.
/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android.d.ts" />
Loading