【问题标题】:Run a callback when a location permission is forbidden禁止位置权限时运行回调
【发布时间】:2019-04-03 17:59:40
【问题描述】:

我目前正在 Laravel 中进行我的项目。我需要获取有关用户的信息(主要是他的位置),以使我的应用程序能够顺利运行;所以我研究了一段时间,了解了地理定位。我有以下代码可以找到用户的位置:

var location;
var latitude;
var longitude;




 function findLocation() {
  var geoSuccess = function(position) {
    location = position;
    latitude = location.coords.latitude;
    longitude = location.coords.longitude;
    console.log("Latitude is " + location.coords.latitude);
    console.log("Longitude is " + location.coords.longitude);
  };
  navigator.geolocation.getCurrentPosition(geoSuccess);
};

问题是,用户需要提供他的位置才能注册他的帐户。因此,当用户禁止位置权限时,我想通知用户提供位置以继续。但我不知道该怎么做。我想做的是:

if(error){
  console.log("You need to provide your location!");  
  // I will do a bunch of stuffs here
 }

那么,我该怎么做呢?任何帮助表示赞赏。

注意:地理位置代码取自 W3Schools.com

【问题讨论】:

标签: javascript php callback geolocation


【解决方案1】:

实际上,我发现 W3Schools 关于地理位置的页面中提到了有关该问题的所有内容。而且,我在那里找到了处理错误和拒绝的方法。

【讨论】:

    【解决方案2】:

    您可以在 getCurrentPosition() 方法中添加回调。

    来源:https://stackoverflow.com/a/18117882/5865284

    navigator.geolocation.getCurrentPosition(showPosition(){
        // Do stuff...
    }, showError(){
        // Do stuff...
    }, {timeout:8000});
    

    值得注意的是,您可能希望超时,以处理提供“Not Now”选项的 Firefox 等浏览器。这是因为按照设计它不会触发错误处理程序,因此我们需要超时来断言我们是否收到了数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-17
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2017-03-01
      • 1970-01-01
      相关资源
      最近更新 更多