Getting old location i used geolocation service


#1

my app is scheduling task and monitor live user but when user logged
in and first time punch in/punch out that time also take correct
location but the issue is i want to take new location every time when
i punch in /punch out,but when i punch in tomorrow it take previous
punch out location, please help.

This is my attendance controller.

.controller('attendanceCtrl',['$scope','$http','$filter','WorkOrder','$ionicPlatform','$interval','$ionicPopup','$rootScope','locationService','$ionicSlideBoxDelegate','$timeout','$state','$ionicLoading',function($scope,$http,$filter,WorkOrder,$ionicPlatform,$interval,$ionicPopup,$rootScope,locationService,$ionicSlideBoxDelegate,$timeout,$state,$ionicLoading){ 

$ionicPlatform.ready(function() {

	var parameters; 
	var promise=null;
	var latlongi; 
	  
	var offset = new Date().getTimezoneOffset(), o = Math.abs(offset);
	var timezone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);
	//initialize bg location service 
	var bgLocationServices = window.plugins.backgroundLocationServices;
	
	//display next month data on '<' arrow click
	$scope.next = function() {        
	    $ionicSlideBoxDelegate.next();
	}; 
	//display previous month data on '>' arrow click
	$scope.previous = function() {  
		$ionicSlideBoxDelegate.previous();
	}; 

    $scope.calendar = {}; 
    $scope.changeMode = function (mode) { 
        $scope.calendar.mode = mode;
    };

    $scope.loadEvents = function () {    
		createRandomEvents();       
    };

    $scope.onEventSelected = function (event) {
    	//$state.go('sidemenu.workorderdetail',{id: event.id,repeat: event.repeat_id});
    };

    $scope.onViewTitleChanged = function (title) {
        $scope.viewTitle = title;
    };

    $scope.today = function () {
        $scope.calendar.currentDate = new Date();
    };

    $scope.isToday = function () {
        var today = new Date(),
        currentCalendarDate = new Date($scope.calendar.currentDate);
        today.setHours(0, 0, 0, 0);
        currentCalendarDate.setHours(0, 0, 0, 0);
        return today.getTime() === currentCalendarDate.getTime();
    };

    $scope.onTimeSelected = function (selectedTime, events, disabled) {
    	$scope.hideTime=true;
    	if($filter('date')(new Date(selectedTime), 'yyyy-MM-dd')==$filter('date')(new Date(), 'yyyy-MM-dd'))
   		{
   			$scope.hideTime=false;
   		}
    };

    //fecth attendance data and display them on calendar
	WorkOrder.all("attendance")
   	.then(function(allattendance){
   		$scope.entry =allattendance;
   		$timeout(function(){
	   		var events = []; 
	        var date = new Date();
	        $scope.no_data=true;
	        if(allattendance.length)
	   		{ 
	   			$scope.no_data=false;
				angular.forEach(allattendance, function(value,key) 
				{ 
					if(events.indexOf(value) == -1) {
					 var attend = new Date(value.date + ' ' + value.time);
					 	events.push({ 
							id 			: value.id,
							type		: value.type,
							logTime		: new Date(attend),
							startTime   : new Date(attend),
							endTime 	: new Date(attend),
							allDay		: false
						});  
					}
				});
				$scope.viewTitle = $filter('date')(new Date(), 'MMMM yyyy');
				$scope.calendar.eventSource = events;
				$scope.$broadcast('eventSourceChanged',$scope.calendar.eventSource);
	   		}
	   	});

   		//intialize Login and Logout button for attendance with resp. to result.
   		var checkAttendanceparameters=[$filter('date')(new Date(), 'yyyy-MM-dd')];
		WorkOrder.query("SELECT * FROM attendance WHERE date=? ", checkAttendanceparameters)
	   	.then(function(res){

	   		$scope.startTime = localStorage.getItem("startTime");
	   		if(res.length>=2)
	   		{
	   			$scope.inserted=true;
	   		}
	   		else if(res.length==1)
	   		{
	   			$scope.logInDisable=true;
	   		}
	   		else 
	   		{
	   			$scope.inserted=false;
	   		}
	   	});
	});

   	//function is called after every 30 mins when user logs in
	function sendGeolocation() {
		var d = new Date();
	    var s = new Date();
	    var e = new Date();
	    s.setHours(23, 00, 0);
	    e.setHours(23, 59, 0);
	    var parameters;
		//check if time is between 11:30 pm - 12:00 am 
	    if(d.getTime()>s.getTime() && d.getTime()<e.getTime())
	    {
	    	// if user hasn't logged out manually
	    	if(localStorage.getItem("endTime")=='' || localStorage.getItem("endTime")==undefined)
	    	{ 
		    	localStorage.setItem("endTime",$filter('date')(new Date(), 'HH:mm:ss'));
				$scope.endTime = localStorage.getItem("endTime");

				parameters=[$filter('date')(new Date(), 'yyyy-MM-dd'),$scope.endTime,'logout','system',localStorage.getItem("company_id"),timezone,'New'];
				//log out user and insert data in local table
				WorkOrder.query("INSERT INTO attendance(date,time,type,logoutby,company_id,timezone,IsSync) VALUES (?,?,?,?,?,?,?)", parameters)
		   		.then(function(response){
			   		localStorage.removeItem("startTime");
			   		localStorage.removeItem("endTime");
			   		localStorage.removeItem("attendanceid");
				});
		   		//fetches user's location and send data to server.
				locationService.get().then(function(latlong){
					var latlong='';
					if(localStorage.getItem("lat")!=undefined && localStorage.getItem("long")!=undefined)
						latlong = localStorage.getItem("lat")+","+localStorage.getItem("long");
					
					$http({ 
						headers : {
						'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
						},
						url:module_url+"worder/addAttendance",
						method:"POST",
						data:{'latlong':latlong,'userid':localStorage.getItem("user_id"),'logoutby':'system','type':'logout','company_id':localStorage.getItem("company_id"),'date':$filter('date')(new Date(), 'yyyy-MM-dd'),'time':localStorage.getItem("endTime"),'timezone':timezone}
					}).success(function(response){
						//console.log(response);
					}).error(function(err){
						//console.log("Error "+err);
					});   

				});
			} 
			//stop the locations service
	    	bgLocationServices.stop();
			if(promise!=null)
				$interval.cancel(promise);
	    } 
	} 
	
	//function is called when clicks Login or logout button
	$scope.attendance=function(start) {

       //if login button is pressed
		if(start)
		{ 	   

			$ionicLoading.show();
			checkAttendanceparameters=[$filter('date')(new Date(), 'yyyy-MM-dd')];
			WorkOrder.query("SELECT id FROM attendance WHERE date=? AND type='login'", checkAttendanceparameters)
		   	.then(function(response){
				if(!response.length){
					//to get time for some android phone
					navigator.globalization.dateToString(
						new Date(),
						function (date) { 
							var time = $filter('date')(new Date(date.value), 'HH:mm:ss');
							if(time=="Invalid Date"){
								time = $filter('date')(new Date(), 'HH:mm:ss');
							} 
							localStorage.setItem("startTime",time);
							$scope.startTime = localStorage.getItem("startTime");
						},  
						function () { 
							//alert('Error getting dateString\n');
						},
						{ formatLength: 'full', selector: 'date and time' }
					);	  
					//get user's currect location
					locationService.get().then(function(latlong){
						if(latlong!='false'){ 
							bgLocationServices.getLocation(function(response){
								localStorage.setItem("lat",response['latitude']);
								localStorage.setItem("long",response['longitude']);
								//alert("response['latitude':"+response['latitude']);
								//alert("response['longitude':"+response['longitude']);
							}, function(err) { 
							});
	                        //Congfigure Plugin
							bgLocationServices.configure({
							     //Both
							     desiredAccuracy: 10, // Desired Accuracy of the location updates (lower means more accurate but more battery consumption)
							     distanceFilter: 1, // (Meters) How far you must move from the last point to trigger a location update
							     debug: true, // <-- Enable to show visual indications when you receive a background location update
							     interval: 30*60*1000, // (Milliseconds) Requested Interval in between location updates.
							     useActivityDetection: true, // Uses Activitiy detection to shut off gps when you are still (Greatly enhances Battery Life)
							     //Android Only
							     notificationTitle: 'Field Track', // customize the title of the notification
							     notificationText: 'Logged In.', //customize the text of the notification
							     fastestInterval: 10*60*1000 // <-- (Milliseconds) Fastest interval your app / server can handle updates    
							});   
							//Start the Background Tracker
							bgLocationServices.start();

							//Register a callback for location updates, this is where location objects will be sent in the background
							bgLocationServices.registerForLocationUpdates(function(location) {
								//alert("in alert of bgloction");
								//alert(JSON.stringify(location));
							    localStorage.setItem("lat",location['latitude']);
							    localStorage.setItem("long",location['longitude']);
							}, function(err) {
							    alert("Error: Didnt get an update", err);
							});

							// Enable background mode while track is playing
							cordova.plugins.backgroundMode.enable(); 
							//insert attendance data to local 'attendance' table			 		
							parameters=[$filter('date')(new Date(), 'yyyy-MM-dd'),localStorage.getItem("lat"),localStorage.getItem("long"),localStorage.getItem("startTime"),'login',localStorage.getItem("company_id"),timezone];
							WorkOrder.query("INSERT INTO attendance(date,lat,long,time,type,company_id,timezone,IsSync) VALUES (?,?,?,?,?,?,?,'New')", parameters);
							//set parameters and flag indicating bg tracking is started
							localStorage.setItem("startLocation","yes");
							$rootScope.startflag='yes';
							$state.reload(); 
							$ionicLoading.hide();
							  
							var ll;
							ll = localStorage.getItem("lat")+","+localStorage.getItem("long");
							//call sendGeolocation function every 30 min
							promise = $interval(function(){sendGeolocation();},30*60*1000); // 30 min for now 
							//send attendance data to server
							$http({ 
								headers : {
								'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
								}, 
								url:module_url+"worder/addAttendance",
								method:"POST",
								data:{'latlong':ll,'userid':localStorage.getItem("user_id"),'logoutby':'','type':'login','company_id':localStorage.getItem("company_id"),'date':parameters[0],'time':parameters[3],'timezone':timezone}
							}).success(function(response){
								//alert(response); 
							}); 
							
						}
						//unable to get user's location
						else{
							$ionicPopup.alert({
			                    title: "Unable to Login",
			                    content: "Please try again."
			                });
						}	
		   			}); 
		   			
		   			$state.reload(); 
		   		}
			});
			$ionicLoading.hide();
		}
		else{
			$scope.inserted=true;
			//check if user has logged in today
			checkAttendanceparameters=[$filter('date')(new Date(), 'yyyy-MM-dd')];
			WorkOrder.query("SELECT id FROM attendance WHERE date=? AND type='login'", checkAttendanceparameters)
		   	.then(function(response){
				 
			if(response.length)
			{
				$ionicLoading.show();
				var latlong='',latlongt=''; 
				//get time thru plugin
				navigator.globalization.dateToString(
					new Date(),
					function (date) {
						var time = $filter('date')(new Date(date.value), 'HH:mm:ss');
						if(time=="Invalid Date"){
							time = $filter('date')(new Date(), 'HH:mm:ss');
						} 
						localStorage.setItem("endTime",time);
						$scope.endTime = localStorage.getItem("endTime");
					}, 
					function () { //alert('Error getting dateString\n'); 
					},
					{ formatLength: 'full', selector: 'date and time' }
				);
				//get user's currect location
				locationService.get().then(function(latlong){
                    if(latlong!='false'){ 
                        latlongt = latlong.split(','); 
						
                   		//localStorage.setItem("endTime",$filter('date')(new Date(), 'HH:mm:ss'));
						//$scope.endTime = localStorage.getItem("endTime");
		                 
						parameters=[$filter('date')(new Date(), 'yyyy-MM-dd'),latlongt[0],latlongt[1],$scope.endTime,'logout','manual',localStorage.getItem("company_id"),timezone,'New'];
						//insert attendance data locally
						WorkOrder.query("INSERT INTO attendance(date,lat,long,time,type,logoutby,company_id,timezone,IsSync) VALUES (?,?,?,?,?,?,?,?,?)", parameters)
						.then(function(response){
							localStorage.removeItem("startTime");
							localStorage.removeItem("endTime");
							localStorage.removeItem("attendanceid");
							$interval.cancel(promise);
						});  

							$http({ 
								headers : {
								'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
								},
								url:module_url+"worder/addAttendance",
								method:"POST",
								data:{'latlong':latlong,'userid':localStorage.getItem("user_id"),'logoutby':'user','type':'logout','company_id':localStorage.getItem("company_id"),'date':parameters[0],'time':parameters[3],'timezone':timezone}
							}).success(function(response){
								  
							}).error(function(err){
							});
							//stop background tracking service and mode
							bgLocationServices.stop();
							localStorage.setItem("startLocation","no");
							$rootScope.startflag='no';
							// disable application if we're still in background and audio is no longer playing
							cordova.plugins.backgroundMode.disable();
							$state.reload();          
					}
					else
                    	$ionicPopup.alert({
			                title: "Unable to Logout",
		                    content: "Please try again."
		                });
                });    
                $ionicLoading.hide();
			}  
				
			});
		}
		
	}
	
});}])

this is geolocation service file.

(function () {'use strict';angular.module('ngApp').service('locationService'['$http','$ionicPopup','$q','$cordovaGeolocation', function($http,$ionicPopup,$q,$cordovaGeolocation){
var that = this;
this.get=function(){
	
	var deferred = $q.defer(); 
    var bgLocationServices = window.plugins.backgroundLocationServices;
      
    bgLocationServices.getLocation(function(location){
		if(location['latitude']!=0){
		    localStorage.setItem("lat",location['latitude']);
		    localStorage.setItem("long",location['longitude']);
		    var lat  = location['latitude']; 
			var longi = location['longitude'];
	        var latlong = lat+','+longi;          
	    	deferred.resolve(latlong); 
		}  
		else
			deferred.resolve('false');
	}, function(err) {
	   //alert("Error: Didnt get an loc", err); 
	}); 

    return deferred.promise;  
}}])})();

and this is my login service file

(function () {"use strict" ngApp.factory('loginService','$http','$location','alertService','$rootScope','$state','$ionicHistory','$timeout','Sync','DB','$ionicPlatform','$ionicLoading','$cordovaPreferences','WorkOrder','$filter','$ionicPopup','locationService','$cordovaBatteryStatus',function($http,$location,alertService,$rootScope,$state,$ionicHistory,$timeout,Sync,DB,$ionicPlatform,$ionicLoading,$cordovaPreferences,WorkOrder,$filter,$ionicPopup,locationService,$cordovaBatteryStatus){ 
    return{ 
        login:function(data,scope){  
        	$ionicLoading.show();
            $http({  
                headers : {
                      'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                url:module_url+"/register/signinCustomer",
                method:"POST",    
                data:data,
          	}).success(function(response){

          		DB.init();
          		$ionicLoading.hide();
				//alert("upto hockeyapp");
				//hockeyapp.forceCrash();
				
            	if(response.action == 'success_login'){
            		localStorage.setItem("firstlogin",'true');

					localStorage.setItem("name",response.user_name);
					localStorage.setItem("mobile_no",response.mobile_number);
					localStorage.setItem("user_id",response.user_id);
				
					localStorage.setItem("company_id",response.company_id);
					localStorage.setItem("profile",response.profile_pic);  
					localStorage.setItem("route",response.route_id);  
					localStorage.setItem("zone",response.zone_id);  
					localStorage.setItem("subzone",response.subzone_id);

					$cordovaPreferences.store('userID', response.user_id);
					$cordovaPreferences.store('companyID', response.company_id);
					$state.go('intro'); 
					Sync.loginData();
					
					$ionicPlatform.ready(function() {
							
							var now = new Date();
							var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
							var date = $filter('date')(now_utc, 'yyyy-MM-dd HH:mm:ss'); 	
					
					var bgLocationServices = window.plugins.backgroundLocationServices;
					locationService.get().then(function(latlong){
						if(latlong!='false'){ 
							bgLocationServices.getLocation(function(response){
								localStorage.setItem("lat",response['latitude']);
								localStorage.setItem("long",response['longitude']);
								//alert("response['latitude':"+response['latitude']);
								//alert("response['longitude':"+response['longitude']);
							}, function(err) { 
							});
						}
						//unable to get user's location
						else{
						}	
		   			}); 
						 
					  $rootScope.$on("$cordovaBatteryStatus:status", function(event, args) {
						if(args.isPlugged) {
							console.log("Charging -> " + args.level + "%");
						} else {
							console.log("Battery -> " + args.level + "%");
						}
					        var result = args.level % 2;
							
						    if(args.level == 30){
						           $ionicPopup.alert({
						                title: "Alert",
						                content: "Battery is low!"
						          });
						          
						    }
					 
					        if(args.level <= 30 && result==0){

					        var parameters;
							parameters=[localStorage.getItem("user_id"),localStorage.getItem("company_id"),localStorage.getItem("mobile_no"),args.level,date];

							WorkOrder.query("SELECT * FROM batterystatus WHERE user_id =? AND battery_status = ?",[localStorage.getItem("user_id"),args.level])
						 	.then(function(res){

						 		if(res.length == 0){

				        		WorkOrder.query("INSERT INTO batterystatus (user_id,company_id,contact_no,battery_status,date_time) VALUES (?,?,?,?,?) ",parameters).then(function(response){
			   						   	//alert("in lloacal");	
								});

									$http({   
									headers : {
										'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
									},
									url:module_url+"worder/batterystatus",
									method:"POST",
									data:{'company_id':localStorage.getItem("company_id"),'user_id':localStorage.getItem("user_id"),'contact_no':localStorage.getItem("mobile_no"),'battery_status':args.level,'date_time':date}
									}).success(function(data){
											//alert(data);
													
									}).error(function(err){
									});
				        		}
				        	});
					    
			           			
							}
					      });

						cordova.getAppVersion(function(version) {	
			          
							
							//WorkOrder.drop("DROP TABLE app_version_report");

							var parameters;
							parameters=[localStorage.getItem("user_id"),localStorage.getItem("company_id"),version,date];
				        
				       		WorkOrder.query("SELECT * FROM app_version_report WHERE user_id =? AND app_version = ?",[localStorage.getItem("user_id"),version])
						 	.then(function(res){
						 		if(res.length == 0){
								
 									WorkOrder.query("INSERT INTO app_version_report (user_id,company_id,app_version,date_time) VALUES (?,?,?,?) ",parameters).then(function(response){
				   						
									});
						 					$http({   
											headers : {
												'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
											},
											url:module_url+"worder/addappversionrepoert",
											method:"POST",
											data:{'company_id':localStorage.getItem("company_id"),'user_id':localStorage.getItem("user_id"),'app_version':version,'date_time':date}
											}).success(function(data){
												//alert("dta: "+data);   					
											}).error(function(err){
											});

						 				}
							   		
							});

			            });




                		if (typeof FCMPlugin != 'undefined') { 
							//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
							//Keep in mind the function will return null if the token has not been established yet.
							FCMPlugin.getToken(
							  function(token){
							    $http({
									headers : { 
										'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
									},
									url:module_url+"/worder/addToken",
									method:"POST",
									data:{token:token,userID:response.user_id}
								}).success(function(tokenresponse){
									//alert(tokenresponse);
								});
							  },
							  function(err){ 
							    //alert('error retrieving token: ' + err);
							  }
							)

							FCMPlugin.subscribeToTopic('all');
						
							FCMPlugin.onNotification(
							  function(data){
								
							  	if(data.wasTapped){
							    	$timeout(function() 
									{
										Sync.synData();
										$state.go('sidemenu.workorder'); 
							    	},500); 
							     
							      //Notification was received on device tray and tapped by the user.
							      //alert(data['location']);
							    }else{
							      //Notification was received in foreground. Maybe the user needs to be notified.
							      alert(data['message']);
							    }
							  },
							  function(msg){
							    //alert('onNotification callback successfully registered: ' + msg);
							  },
							  function(err){
							    //alert('Error registering onNotification callback: ' + err);
							});
						}
						});
                    alertService.add('success', 'Welcome to FieldTrack.');                       
               	}else if(response== 'no_access'){
                	alertService.add('warning', 'You Have No Access.');  
                    $state.go('login');
                }else {
                  	alertService.add('warning', 'Email ID or Password are incorrect.');
                	$state.go('login');
          		}
    		}).error(function(err){ 
          		$ionicLoading.hide();
          		alert("Something went wrong. Please check your Internet Connection.");
          	});
    	},
        getLoggedInUserData:function(){ 
			var loggedInUserData = $http.get(module_url+"/register/getLoggedInUser",{headers : {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}});
			return loggedInUserData;
		},
        logout:function(){ 
        	
        	$ionicLoading.show();
        	Sync.logoutData();
	        $http({
                headers : {
                      'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                url:module_url+"register/logoutUser",
                method:"POST",
                data:localStorage.getItem("user_id"),   
          	}).success(function(response){ 
          	    Sync.clearDB(); 
                localStorage.removeItem("route");  
                localStorage.removeItem("zone");  
                localStorage.removeItem("subzone");  
                localStorage.removeItem("len");
				localStorage.removeItem("devicestatus");
				localStorage.removeItem("name");
                localStorage.removeItem("mobile_no");
                localStorage.removeItem("company_id");
              	localStorage.removeItem("user_id"); 
				localStorage.removeItem("profile"); 
				localStorage.setItem("devicestatus",0); 
				localStorage.removeItem("worder_status");	
				localStorage.removeItem("workOrderCount");
				$ionicLoading.hide(); 				    
				$location.path('/login');
				alertService.add('info', 'Logout successfully.');
			    
			    $timeout(function () { 
			    	var bgLocationServices = window.plugins.backgroundLocationServices;
			    	bgLocationServices.stop();
					$rootScope.startflag = "wait";
					// disable application if we're still in background and audio is no longer playing
					cordova.plugins.backgroundMode.disable();

					/*$ionicHistory.clearCache();
			        $ionicHistory.clearHistory();
			        $ionicHistory.nextViewOptions({
			            disableBack: true,
			            historyRoot: true
			        }); */
			        
			    },500);
		        
      		}).error(function(){
      			$ionicLoading.hide();
      			alert("Something went wrong. Please try again later.");
      		}); 
    	},
        islogged:function(){
           var $checkSessionServer = $http.post(module_url+'/register/checkIsLoggedIn',{headers : {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}});
           return $checkSessionServer;
        },
		alreadyLoggedIn:function(){ 
			
        	if(localStorage.getItem("user_id")!=undefined)
          		$state.go('sidemenu.workorder');
		}, 
        refreshView:function(){
           	$timeout(function(){
            	$ionicHistory.clearCache([$state.current.name]).then(function() {
            		$state.reload();
            	});
          	},100);
        }         
	}}]);})();