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

前端 未结 3 531
余生分开走
余生分开走 2020-12-09 10:11

Apart from setting a cookie the first time round, is there a way of detecting whether a user has already given permission for navigator.geolocation to return the lat/long of

3条回答
  •  执笔经年
    2020-12-09 11:06

    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

提交回复
热议问题