Reputation: 279
I am working on a application and in this application i want to get getCurrentPosition.I have created a PWA app and also implemented offline mode. So when internet is available , internet is not available in both cases it working fine but when cellular network in not available (Flight mode) then geolocation.getCurrentPosition function returning empty value.
Service Worker Code :-
var CACHE_NAME = 'geolocation_cache';
// Install a service worker
self.addEventListener('install', event => {
event.waitUntil( async function(){
let cache= await caches.open(CACHE_NAME)
await cache.addAll(
[
'/manifest.json',
'/geolocationoffline.html',
]
);
}())
});
// Update or Activate a service worker
self.addEventListener('activate', event =>{
event.waitUntil( async function(){
let cacheWhitelist = ['geolocation_cache'];
let cacheNames = await caches.keys();
await Promise.all(
cacheNames.map(element => {
if(cacheWhitelist.indexOf(element) === -1){
return caches.delete(element);
}
})
)
}())
});
// Cache and return requests
self.addEventListener('fetch', event => {
event.respondWith( async function(){
const availableCache= await caches.open('geolocation_cache');
if(event.request.url.indexOf('/geolocation') < 0){
const availableCache= await caches.open('geolocation_dynamic');
try{
const networkResponse = await fetch(event.request);
const cachedResponse = await availableCache.match(event.request);
if(cachedResponse) return cachedResponse;
const networkResponse = await fetch(event.request);
event.waitUntil(
availableCache.put(event.request, networkResponse.clone())
);
return networkResponse;
}
catch(err){
const availableCache= await caches.open('geolocation_cache');
let response=await availableCache.match('/geolocationoffline.html');
return response;
}
}
else{
return await fetch(event.request);
}
}())
});
Offline Page:-
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
</head>
<body>
<div id="root">
<h3>Geo Location Offline</h3>
<p class="time-info"></p>
<p class="page-info"></p>
</div>
<script>
navigator.geolocation.getCurrentPosition(function(position){
document.getElementsByClassName("page-info")[0].innerText=`lat=${position.coords.latitude} long=${position.coords.longitude}`;
document.getElementsByClassName("time-info")[0].innerText=`timeStamp=${position.timestamp}`;
});
</script>
</body>
</html>
Upvotes: 0
Views: 351
Reputation: 163438
That's normal. Most devices also turn off GPS capability when in flight mode.
Upvotes: 1