javascript - 是否有测试来确定页面是否要求位置授权?

标签 javascript location

如果用户的浏览器请求允许我们确定用户的位置,我想在页面上显示信息,但是如果浏览器已经通过身份验证可以向我们提供他们的信息,我不想尝试显示此信息地点。

有什么好的方法吗?

详细。我想显示一条消息说“请点击‘允许这些人获取您的位置’的框”,因为在用户测试中我们发现用户看不到对话并感到困惑。

但是,即使我们在他们通过位置查找页面时获得他们的许可,这也会导致我们闪现帮助消息。存储他们给予我们许可的事实并没有帮助,因为他们可能会撤销该许可,而我们不会知道。

有什么想法吗?

干杯 马克。

最佳答案

您可以将错误回调交给 getCurrentPosition() 来确定用户是否已拒绝跟踪/位置无法确定 (spec)。

此外,我会设置一个 TimeOut,它会在一定时间后提示您的消息,因为在这种情况下,用户很可能会忽略浏览器对话框。

示例代码:

function getLocation(){
  if (navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(showPosition,showError);
     // set a Timeout, after which the user gets prompted
     // ugly global var but you could prevent this e.g. with a closure
     t = window.setTimeout(
              function(){alert("Please allow us to locate you;) !")},3000
         );
  } else {
     alert("Geolocation is not supported by this browser.");
  }
}
function showPosition(position){
      alert("Latitude: " + position.coords.latitude + " - Longitude: " + position.coords.longitude);
      // position could be determined, clear the timeout
      window.clearTimeout(t);   
}
function showError(error){
  // an error occured, clear the timeout as well
  window.clearTimeout(t);
  switch(error.code) {
    case error.PERMISSION_DENIED:
      alert("User denied the request.");
      // Do stuff here, etc. ask the user to please allow the request
      break;
    case error.POSITION_UNAVAILABLE:
      alert("No Location information available.");
      break;
    case error.TIMEOUT:
      // user probably didn't recognize the browser dialog
      alert("The request timed out.");
      break;
    case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.");
      break;
    }
}

但是,您仍然可以存储权限并进行检查。如果他们撤销了他们的许可,您将遇到错误回调,您可以在其中采取相应的措施。

关于javascript - 是否有测试来确定页面是否要求位置授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461222/

相关文章:

javascript - 是否可以在不包括 Jquery 中的嵌套元素的元素上注册点击?

javascript - 具有最小尺寸的动态页脚尺寸

php - 查找最近的城市,例如 oodle.com

c# - 可执行位置不同

android - 获取坐标的平均精度

javascript - 使用 Javascript 在新选项卡中启用打开链接

javascript - 当我直接粘贴 URL 时,AngularJs View 不会加载

java - 如何在已动态添加的JLabel 的JPanel 中获取Location()?

android - 如何使用 ActivityRecognition API 检测转换中的变化?

location - 谷歌语音 v2 : 'Expected resource location to be global, but found europe-west4 in resource name.' ,