当定位服务关闭和打开时,地理位置不起作用



我有一个由按钮单击触发的函数,用于检查地理位置。当地理位置处于打开状态时,它在手机上工作正常,当关闭时,如预期的那样显示一条消息。当首先关闭手机的位置服务,单击按钮(按预期弹出消息)时,就会出现问题,然后如果用户在应用程序仍处于打开状态时重新打开位置服务,然后再次单击该按钮,仍然会弹出相同的"无位置服务"消息。

有没有办法在每次单击按钮时检查手机的位置服务是打开还是关闭? 在Android和IOS上获得相同的结果。

法典:

$(document).ready(function () {
    $('#smallScreenGeolocate').on('click', function(){
     getCurrentLocation();
     });
});
function getCurrentLocation () {
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(addGeolocationMarker, locationError);
    return true;
}
else {
    alert("Browser doesn't support Geolocation. Visit http://caniuse.com to discover browser support for the Geolocation API.");
    return false;
}
}

从另一个 SO 帖子中查看此答案 https://stackoverflow.com/a/14862073/6539349

您必须按照此处的建议检查错误是什么 http://www.w3schools.com/html/html5_geolocation.asp

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
   x.innerHTML = "Latitude: " + position.coords.latitude +
   "<br>Longitude: " + position.coords.longitude;
}

getCurrentPosition() 方法的第二个参数showError用于处理错误。它指定在无法获取用户位置时要运行的函数:

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

最新更新