skip to Main Content

I want to do tasks after the user makes no decision on the location’s permission. I have tried the following:

navigator.geolocation.getCurrentPosition((pos) => {
    let lat = pos.coords.latitude;
    let long = pos.coords.longitude;
    console.log(lat, long);
    console.log("User granted permission");
}, (error) => {
    console.error(error);
    console.error("User didn't grant permission");
}, {
    timeout: 3000,
    maximumAge: 3000,
    enableHighAccuracy: true
});

I have set timeout and maximumAge attributes to 3000 ms, but it didn’t work anymore. The error will only be triggered if the user closes the permission pop-up. How can I detect if the user makes no decision after 3 seconds? Thank you.

2

Answers


  1. You can add setTimeout call before getCurrentPosition and clear timeoutID if the user does something:

    var timeoutID = window.setTimeout(() => {
        console.log('user makes no decision');
        // do 1
    }, 3000);
    
    navigator.geolocation.getCurrentPosition((pos) => {
        timeoutID && window.clearTimeout(timeoutID);
        // do 2
    }, (error) => {
        timeoutID && window.clearTimeout(timeoutID);
        // do 3
    }, {});
    
    Login or Signup to reply.
  2. With some code updates you can achieve it, like thus way

    navigator.geolocation.getCurrentPosition(
      (pos) => {
        // Handle successful geolocation request
        let lat = pos.coords.latitude;
        let long = pos.coords.longitude;
        console.log(lat, long);
        console.log("User granted permission");
      },
      (error) => {
        if (error.code === error.TIMEOUT) {
          console.error("Timeout error: User didn't grant permission within the specified time");
        } else {
          console.error(error);
          console.error("User didn't grant permission");
        }
      },
      { timeout: 3000, maximumAge: 3000, enableHighAccuracy: true }
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search