仅请求地理位置信息以响应用户手势?

Only request geolocation information in response to a user gesture?

我刚刚更新到 Chrome 64 并开始在我们的网络应用程序中注意到这条消息:

[Violation] Only request geolocation information in response to a user gesture.

这似乎过于严格了。在 Google 地图中导航时,我不必重复单击 "Update location"。位置轮询的替代方法是什么?

我们目前正在使用以下代码:

let locInt = self.setInterval(function(){
    navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
},5000);

我们的应用程序基于位置并依赖于不断更新的位置。这里的首选方法是什么?

watchPosition() 方法允许您注册一个处理程序,每次设备位置发生变化时浏览器都会自动调用该处理程序。这比轮询更可取。

id = navigator.geolocation.watchPosition(success[, error[, options]])

违规与投票无关。这是由于尝试在页面加载时访问地理位置引起的。仅应在用户做出点击或点击等“手势”后请求地理位置访问权限。

document.querySelector('.permission-granted-button').addEventListener('click', () => {
  navigator.geolocation.watchPosition(successCallback, errorCallback, optionsObject);
});

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition

Google not 似乎有一个 recommendation 在页面加载时加载地理定位:

Users are mistrustful of or confused by pages that automatically request their location on page load. Rather than automatically requesting a user's location on page load, tie the request to a user's gesture, such as a tapping a "Find Stores Near Me" button. Make sure that the gesture clearly and explicitly expresses the need for the user's location.

使用watchPosition()getCurrentPosition()都没有关系:

Lighthouse collects the JavaScript that was executed on page load. If this code contains calls to geolocation.getCurrentPosition() or geolocation.watchPosition(), and geolocation permission was not already granted, then the user's location was requested.

我们还注意到,自 Chrome 更新以来,在获取用户地理位置方面存在大量延迟。

我找到了解决方案!这个问题的存在是因为 "HTTP"。如果你想使用像 "geolocation" 这样的 javascript API,你的服务器或本地服务器必须是 HTTPS 协议而不是 HTTP。