alcatrazbr
6/19/2016 - 3:32 AM

Código para pegar o gelocalização, inclusive em background

Código para pegar o gelocalização, inclusive em background

        function onDeviceReady() {
           // Iniciar banco de dados local (DatiJS)

           /**
           * 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.
               // jQuery.post(url, JSON.stringify(location));               
               var lat  = location.latitude;
               var lng = location.longitude;

               var GeoLocation = {
                   Lat : lat,
                   Long : lng, 
                   idConfig : glbWebId,
                   dthrinsert : moment().format('YYYY-MM-DD HH:mm:ss')
               }
               // Desabilitado por não implementar a rotina
               sendLocation(GeoLocation);

               /*
               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.
               */
               backgroundGeolocation.finish();
           };

           var failureFn = function(error) {
               console.log('BackgroundGeolocation error');
               alert('BackgroundGeolocation error');
           };

           // BackgroundGeolocation is highly configurable. See platform specific configuration options
           backgroundGeolocation.configure(callbackFn, failureFn, {
               desiredAccuracy: 10,
               stationaryRadius: 20,
               distanceFilter: 30,
               notificationIconColor: '#4CAF50',
               notificationTitle: 'Renda Plus',
               notificationText: 'GPS ENABLED',
               interval: 20000, // <!-- poll for position every minute
               fastestInterval: 120000,
               debug: false, // <-- 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.
           backgroundGeolocation.start();
}


        // pega a localizacao atual do dispositivo
        function getGeoLocation() {
            clearInterval(glbInterGeolocation);
            
            var last = window.localStorage.getItem('geoLocation');
            if (last === undefined) {
                last = moment().subtract(1, 'hours');
            }
            last = moment(last, 'YYYY-MM-DD HH:mm:ss');
            var now = moment();

            iTime = last.diff(now, 'minutes');

            if (iTime < 0 ) {
                navigator.geolocation.getCurrentPosition(onSuccessGeolocation, onErrorGeolocation);                
            } else {
                glbInterGeolocation = setInterval(function(){ getGeoLocation() }, 20000);
            }


        }

        // conseguiu pegar a localizacao envia para o servidor
        function onSuccessGeolocation(position) {
            var element = document.getElementById('geolocation');
            // element.innerHTML = 'Latitude: '           + position.coords.latitude              + '<br />' +
            //                     'Longitude: '          + position.coords.longitude             + '<br />' +
            //                     'Altitude: '           + position.coords.altitude              + '<br />' +
            //                     'Accuracy: '           + position.coords.accuracy              + '<br />' +
            //                     'Altitude Accuracy: '  + position.coords.altitudeAccuracy      + '<br />' +
            //                     'Heading: '            + position.coords.heading               + '<br />' +
            //                     'Speed: '              + position.coords.speed                 + '<br />' +
            //                     'Timestamp: '          + position.timestamp                    + '<br />';

            var lat = position.coords.latitude;
            var lng = position.coords.longitude;

            var GeoLocation = {
                Lat : lat,
                Long : lng, 
                idConfig : glbWebId,
                dthrinsert : moment().format('YYYY-MM-DD HH:mm:ss')
            }

            // sendLocation(GeoLocation);
            
        }


        function sendLocation(GeoLocation){
            $.ajax({
                url: 'http://'+host+'geolocation/',
                type: 'POST',
                dataType: 'json',
                data: GeoLocation,
            })
            .done(function() {
                var NextGeoLocation = GeoLocation.dthrinsert.add(5, 'minutes');
                window.localStorage.setItem('geoLocation', NextGeoLocation.format('YYYY-MM-DD HH:mm:ss'));
                console.log("success");
            })
            .fail(function(data) {
                console.log("error");
                console.debug(data);
            })
            .always(function() {
                console.log("complete");
                // play('checkpoint');
                myApp.addNotification({
                    message: '<i class="fa fa-map-marker fa-lg margin-bottom"></i> Nova localização',
                    hold: 2000,
                    button:  false
                });

                glbInterGeolocation = setInterval(function(){ getGeoLocation() }, 20000);
            });
        }


        // onError Callback receives a PositionError object
        //
        function onErrorGeolocation(error) {
            alert('code: '    + error.code    + '\n' +
                  'message: ' + error.message + '\n');
            glbInterGeolocation = setInterval(function(){ getGeoLocation() }, 20000);
        }