Is there a way of detecting whether a user has already given permission to use navigator.geolocation?

£可爱£侵袭症+ 提交于 2019-11-28 09:06:13

What about using localStorage which should be supported by all html5 browsers (that support geoLocation)

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get latitude and longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;

    localStorage['authorizedGeoLocation'] = 1;
}

function errorFunction(){
    localStorage['authorizedGeoLocation'] = 0;
}

function checkauthorizedGeoLocation(){ // you can use this function to know if geoLocation was previously allowed
    if(typeof localStorage['authorizedGeoLocation'] == "undefined" || localStorage['authorizedGeoLocation'] == "0" ) 
        return false;
    else 
        return true;
}

And then you check using the below function :

alert(checkauthorizedGeoLocation());

This is the jsfiddle if you need to check

According to the spec, no - there's just the three methods on navigator.geolocation. However saving to a cookie or local storage is probably perfectly suitable - the permission is also stored in the user agent, so it should work correctly as the user moves between browsers.

Please see this answer on how to do it using the Permissions API: Check if Geolocation was allowed and get Lat Lon

Works without prompting the user if permission was granted previously.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!