javascriptfirefoxmobile-safarinavigatorw3c-geolocation

GeolocationPositionError: Position acquisition timed out


I want to retrieve user geolocation on click of the button in.

I use navigator.geolocation (pure js) It worked for some time (with code below), better or worse (used to work on the seccond time you accepted prompt for localization permissions on Firefox, and with every accept on Safari) but now it stopped working completly on Firefox and Safari (ios) (On Chrome and Edge it works fine)

I'm getting GeolocationPositionError {code: 3, message: "Position acquisition timed out"} error on Firefox after accepting localization. On Safari it stopped asking me for permisions, just sends "Fail 2" alert. Please point me to the correct solution how to solve that... My code:

if (!navigator.geolocation) {
    alert("Fail 1")
} else {
    isOnline();
    if (internet){ 
        getAddress().then( l =>{
            const [latitude, longitude] = l
            formData.append("latitude", latitude);
            formData.append("longitude", longitude);
            sendRequest()
        }).catch(e =>{
            console.log(e) // GeolocationPositionError {code: 3, message: "Position acquisition timed out"}
            if (internet){
                alert("Fail 2")
            }else{
                noInternet()
            }
        }) 
    }else{
        noInternet()
    }
}

getAddress function:

export async function getAddress() {
    const position = await getCoordinates(); 
    let latitude = position.coords.latitude;
    let longitude = position.coords.longitude;
    return [latitude, longitude] 
}

getCoordinates function:

async function getCoordinates() {
    return new Promise(function(resolve, reject) {
      navigator.geolocation.getCurrentPosition(resolve, reject, navigatorLocationOptions);
    });
}

navigatorLocationOptions: (I've tried different combinations and none of them seem to solve the issue)

const navigatorLocationOptions = {
    enableHighAccuracy: true,
    timeout: 5000,
    // maximumAge: 100000
};


Solution

  • Ok, I think the code was ok, problems came from the browser. If you encounter a similar problem, there are two steps to follow:

    1. Make sure the webpage is protected (https). (Localization doesn't work on http)

    2. Try both options of page reload:

      • Ctrl + Shift + R
      • Ctrl + F5

      They seem to work a bit differently even though I didn't find the reason for it.