A look at the geolocation HTML element and how it works
Topic: JavaScript
Topic: JavaScript
The <geolocation> HTML element does exactly what you might think it does. It’s a dedicated element that gets the user’s location, either once or continuously. The options are set using HTML attributes instead of JavaScript, but JavaScript is still needed. However, <geolocation> requires fewer lines of JavaScript and also offers superior error and permission handling. In fact, the <geolocation> element started off as an all-purpose <permission> element, but is now dedicated to handling geolocation.
<geolocation> HTML 元素的作用正如其名。它是一个专门用于获取用户位置(一次性或持续获取)的元素。选项通过 HTML 属性而不是 JavaScript 进行设置,但仍然需要 JavaScript。不过,<geolocation> 需要的 JavaScript 代码行数更少,并且提供了更出色的错误和权限处理。事实上,<geolocation> 元素最初是一个通用的 <permission> 元素,但现在专门用于处理地理位置。
Fewer lines of code is always a good thing, but it’s the permission prompt that’s key here. When using the aging Geolocation JavaScript API, denying permission at any point can lock the user out with no way to recover unless they change the browser or operating system permissions manually. This can be a painful experience, especially for users that aren’t tech-savvy. Plus, as developers, we have to get the Permissions API involved.
代码行数越少总是件好事,但这里的重点在于权限提示。在使用老旧的 Geolocation JavaScript API 时,在任何阶段拒绝权限都可能导致用户被锁定且无法恢复,除非他们手动更改浏览器或操作系统的权限。这可能会带来糟糕的体验,尤其是对于不懂技术的用户而言。此外,作为开发者,我们还必须引入 Permissions API。
Whereas, the <geolocation> element offers:
而 <geolocation> 元素则提供:
- Better error handling, and where applicable, recovery handholding
- 更好的错误处理,以及在适用情况下的恢复引导
- User-controlled permission prompting, even if the user denied permission previously
- 用户控制的权限提示,即使用户之前拒绝了权限
- Auto-location if the user granted permission previously
- 如果用户之前已授予权限,则自动获取位置
- A styleable granted state via the
:grantedCSS pseudo-class - 通过
:grantedCSS 伪类提供可设置样式的已授权状态
<geolocation> is better in every way except browser support (it requires Chrome 144+), so in this article, I’ll explain how to use it alongside the older current Geolocation JavaScript API so that users get the better experience, if the new element is availab...