Geolocation function buggy on mobile

This script seems to run successfully about 80% of the time on mobile, but it fails silently now and then. I ran console.log statements on it and plugged it into my PC and the console just returns >Getting location…

Most of the time, the user has to reboot the phone to get it working again. Isn’t there a safer way to run this script?

function getLocation() {
        console.log("Getting location...");
        navigator.geolocation.getCurrentPosition(showPosition);
    }

    function showPosition(position) {
        console.log("Location received:", position);
        
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        
        console.log("Latitude:", latitude);
        console.log("Longitude:", longitude);
        
        document.getElementById("Latitude").value = latitude;
        document.getElementById("Longitude").value = longitude;
    }