Vaibhav Gole
Vaibhav Gole

Reputation: 165

Geolocation reporting in Ionic app Background

I intend to get users geolocation even when the app sits dormant in the background and store the same in the database. I'm using katzer's Cordova Background Plug-in, When I try to access navigator.geolocation.getCurrentPosition inside backgroundMode.onactivate function, nothing happens, Whereas when I try passing hard coded values api is called, data is stored in database.

following is my code

document.addEventListener('deviceready', function() {
    // Android customization
    cordova.plugins.backgroundMode.setDefaults({
        text: 'Doing heavy tasks.'
    });
    // Enable background mode
    cordova.plugins.backgroundMode.enable();

    // Called when background mode has been activated
    cordova.plugins.backgroundMode.onactivate = function() {
        console.log('inside background')

        a();
    }

    var a = function() {
        console.log('a called')
        navigator.geolocation.getCurrentPosition(function(pos) {

            console.log('inside navigate');
            var data = {
                Lati: '123456',
                Longi: '132456',
                //LoginID: JSON.parse(window.localStorage.getItem('LoginId'))
                EmpCode: localStorage.getItem('LoginId')
            };

            $http.post("https://app.sbismart.com/bo/ContactManagerApi/UpdateEmployeeLoc", data).success(function(rsdata, status) {
                console.log('inside rsdata');
                console.log(data.Lati + "," + data.Longi);
            })
        }, function(error) {
            alert('Unable to get location: ' + error.message);
        });
    }


}, false);

Upvotes: 0

Views: 287

Answers (1)

IamKarim1992
IamKarim1992

Reputation: 646

cordova.plugins.backgroundMode.onfailure = function(errorCode) {
console.log(errorCode)
};`

and check as to why is it failing....then again u need to run the locationService function in a timeout function in the background to get updated about the location and check the location from previously got location. Something like this...

cordova.plugins.backgroundMode.onactivate = function () {
        setTimeout(function () {
           a();

        }, 5000);
    }

Hope this helps.

Upvotes: 1

Related Questions