【问题标题】:geolocation.getCurrentPosition on Safari on iOSiOS 上 Safari 上的 geolocation.getCurrentPosition
【发布时间】:2021-03-30 11:02:28
【问题描述】:

我正在使用下面的代码(取自 w3schools.com)并且仅在 Safari + iOS 上它会传递错误“permission_denied”。

我正在使用 https,Safari 访问我页面上的位置的权限设置为“允许”并且我没有使用 webView(如almost identical question 中所述)。

它可以在带有 iPadOS 或 macOS 的 Safari 上完美运行,也可以在 iOS 上的 Firefox 上完美运行。

iOS 上的 Safari 有什么特别之处,如何解决?

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;
}

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;
  }
}

【问题讨论】:

  • 自行解决:有 两个 位置可以打开位置服务: 1. 转到设置 > 隐私 > 位置服务 2. 使用 Safari 时 > 打开查看菜单> 点击 aA > 网站设置

标签: ios geolocation mobile-safari


【解决方案1】:

在网页中执行以下操作/或使用带有弹出对话框的导航器

 var options = {
  enableHighAccuracy: true,
  timeout: 7000,
  maximumAge: 0
};

function log(data) {
  const tag = document.createElement('p');
  tag.textContent = data;
  document.body.appendChild(tag);
}

function success(pos) {
  var crd = pos.coords;
  console.log('Successfully determined a user position:', crd);

  log('Your current position is:');
  log(`Latitude : ${crd.latitude}`);
  log(`Longitude: ${crd.longitude}`);
  log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

或者

$scope.watchId = navigator.geolocation.watchPosition(function (position) {
                        if ($scope.t1 == 0) {
                            $scope.t1 = position.timestamp;
                        } else {
                            if (Math.abs($scope.t1 - position.timestamp) > 5000) {
                                $scope.t1 = position.timestamp;
                                SellerRef.update({ Location: { Lat: position.coords.latitude, Long: position.coords.longitude } })
                            }
                        }
    
                    },
                        function (error) {
                            if (error.code == 1) {
                                  $scope.showAlert("An error occured \n" + " Please goto Settings->Privacy->LocationServices and give permission for " + bowser.name + " which is your browser ");
                            }
    
                        }
                    ); 

用于在应用内加载您的网络

  • 然后使用webView,只需将位置权限描述添加到info.plist文件中。
  • 添加NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescriptionNSLocationUsageDescription

什么是地理定位错误,看here

navigator.geolocation.getCurrentPosition(success => {
  /* Do some magic. */
}, failure => {
  if (failure.message.startsWith("Only secure origins are allowed")) {
    // Secure Origin issue.
  }
});

在 manifest.webapp 文件中包含/设置“required_features”选项:

{
  "required_features": ["geolocation"]
}

用户:

在 iPhone 上:

Settings -> Location Services -> [your Browser] [apple ref][1]

Chrome 需要 https 才能使用地理位置


疑难解答&&权限检查/调试日志

检查,用户的操作系统和浏览器BOTH开启了定位服务,用户的浏览器支持检查定位服务

    // options for current position
    const navigatorLocationOptions = {
      enableHighAccuracy: true,
      timeout: 7000,
      maximumAge: 0
    };
 
    // does browser have geo services enabled
    navigator.permissions.query({name:'geolocation'})
      .then((result) => {
        
        if (result.state === 'granted') {// you are good
          navigator.geolocation.getCurrentPosition(position => {
             console.log('granted user location permission', position );
              
             //.. do your stuff

          }, (error) => {
            // OS services are not enabled
            console.log('Please turn on OS located services', navigator);
            errorLocation();
          }, navigatorLocationOptions);

        } else {
          // browser issues seriveces
          console.log('Browser location services disabled', navigator);
          errorLocation();
        }
      }, (error) => {
        /* Browser doesn't support querying for permissions */
        console.log('Please turn on BROWSER location services', navigator);
        errorLocation()
      }
    );


    //handle errors
    function errorLocation() {
      ...
    }

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多