Фоновое географическое расположение Кордовы:
Сначала вам нужно добавить плагин backgroudgeolocation. , который помогает вам предоставлять услуги, которые необходимо добавить в ваше приложение.
Использование плагина
Плагин создает объект window.plugins.backgroundGeoLocation с помощью методов
configure(success, fail, option),
start(success, fail)
stop(success, fail).
Установка плагина:
плагин cordova добавить https://github.com/christocracy/cordova-plugin-background-geolocation.git АЧТУНГ! Если вы не используете Cordova 5.x, вы должны использовать ветку с тегами # cordova-4.x для установки плагина, как это (поскольку Cordova перешла на npm)
плагин cordova добавить https://github.com/christocracy/cordova-plugin-background-geolocation.git#cordova-4.x Полный пример:
//
//
// after deviceready
//
//
// Your app must execute AT LEAST ONE call for the current position via standard Cordova geolocation,
// in order to prompt the user for Location permission.
window.navigator.geolocation.getCurrentPosition(function(location) {
console.log('Location from Phonegap');
});
var bgGeo = window.plugins.backgroundGeoLocation;
/**
* This would be your own callback for Ajax-requests after POSTing background geolocation to your server.
*/
var yourAjaxCallback = function(response) {
////
// IMPORTANT: You must execute the #finish method here to inform the native plugin that you're finished,
// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
//
//
bgGeo.finish();
};
/**
* This callback will be executed every time a geolocation is recorded in the background.
*/
var callbackFn = function(location) {
console.log('[js] BackgroundGeoLocation callback: ' + location.latitude + ',' + location.longitude);
// Do your HTTP request here to POST location to your server.
//
//
yourAjaxCallback.call(this);
};
var failureFn = function(error) {
console.log('BackgroundGeoLocation error');
}
// BackgroundGeoLocation is highly configurable.
bgGeo.configure(callbackFn, failureFn, {
url: 'http://only.for.android.com/update_location.json', // <-- Android ONLY: your server url to send locations to
params: {
auth_token: 'user_secret_auth_token', // <-- Android ONLY: HTTP POST params sent to your server when persisting locations.
foo: 'bar' // <-- Android ONLY: HTTP POST params sent to your server when persisting locations.
},
headers: { // <-- Android ONLY: Optional HTTP headers sent to your configured #url when persisting locations
"X-Foo": "BAR"
},
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
notificationTitle: 'Background tracking', // <-- android only, customize the title of the notification
notificationText: 'ENABLED', // <-- android only, customize the text of the notification
activityType: 'AutomotiveNavigation',
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false // <-- enable this to clear background location settings when the app terminates
});
// Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
bgGeo.start();
// If you wish to turn OFF background-tracking, call the #stop method.
// bgGeo.stop()
ПРИМЕЧАНИЕ. Плагин включает org.apache.cordova.geolocation в качестве зависимости. Вы должны включить GeoLocation Кордовы на переднем плане и попросить пользователя принять службы определения местоположения, выполнив #watchPosition или #getCurrentPosition.
Сначала скопируйте SampleApp из репозитория в любую желаемую папку (например, tmp).
$ cp -R cordova-plugin-background-geolocation/example/SampleApp ./tmp
$ cd tmp/SampleApp
$ cordova plugin add https://github.com/christocracy/cordova-plugin-background-geolocation.git
$ cordova platform add ios
$ cordova build ios
Для получения дополнительной информации щелкните ссылку ниже:
Геолокация фона Кордовы
Ура, удачного кодирования.
23.02.2016