I have an application for organizing on-the-field employees. These employees usually go around town to complete jobs. I also have an admin panel through which I allocate different jobs to these employees.
The thing is, I need to know where each employee is at every given moment in order to be able to allocate a job based on their location (I wouldn't want to allocate a job to a tech who is 10 kilometers away).
I have a backend system which stores the current geolocation of each user and a map which displays their location. Now the last thing I need is to be able to track their location when they have closed the app or locked their phone.
My application is actually just a PWA, so I dont have any native control of the device. I have successfully registered a service-worker and added the following task:
serviceWorkerRegistration.register({
onSuccess: () => {
const user = JSON.parse(localStorage.getItem(KEY))?.user
setInterval(() => {
if (user.currentUser?._id !== undefined) {
displayNotification(user === undefined ? "Undefined" : user.currentUser._name)
navigator.geolocation.getCurrentPosition(e => {
const data = new FormData()
data.append("user", JSON.stringify({
_id: user.currentUser._id,
_last_lat: e.coords.latitude,
_last_lon: e.coords.longitude
}))
axios.post(API_URL + '/api/user/update', data)
.then(() => displayNotification("Data sent!"))
}, error => {
alert(error.code)
})
}
}, 30000)
}
});
Here is the displayNotification function:
const displayNotification = str => {
if (Notification.permission == 'granted') {
navigator.serviceWorker.getRegistration().then(reg => {
reg?.showNotification(str);
});
}
}
This works while the user uses the application (I get both notifications - the _name of the user and Data Sent!. As soon as I exit the application, I only get the _name of the current user which means that it is not executing the fetch.
What is the reason for this? Am I doing something wrong? How do I successfully put this process in the background?