追踪用户在您的网站上的位置

2025-06-04

追踪用户在您的网站上的位置

大家好👋

在本文中,我们将了解如何访问我们网站上的用户位置。

追踪用户位置并非总是必要的,但如果您正在构建类似位置共享应用、地图相关应用,或者希望根据用户位置提供定制化结果,则需要访问用户位置。我所说的应用是指基于 Web 的应用。

那么我们如何才能获取用户的位置呢?

现代浏览器几乎提供了我们应用中所需的一切功能,以提升用户体验。这里就涉及到了Geolocation API浏览器提供的 Web API,用于在用户同意的情况下访问用户的位置信息。

文章末尾有实时链接可供尝试。

什么是地理定位 API?

Geolocation API是一个 Web API,允许 Web 内容访问设备的位置。

使用需要许可Geolocation API

实现📍

让我们了解一下API的实现。

我们可以从浏览器的对象访问 API window.navigator

检查Geolocation API支持

if (Boolean(window.navigator.geolocation)) {
  // It supports
  ...
}
Enter fullscreen mode Exit fullscreen mode

地理位置界面🗺️

geolocation是获取、跟踪和取消跟踪位置时需要访问的主要方法。它有三个属性(方法):

  • getCurrentPosition
  • watchPosition
  • clearWatch

当前位置📌

要获取设备的当前位置,我们将使用getCurrentPosition方法。此方法会将电流传递positionpositionCallback,如果error,则会将error对象传递给errorCallback

window.navigator.geolocation.getCurrentPosition(
    positionCallback,
    errorCallback
);
Enter fullscreen mode Exit fullscreen mode

位置回调

function positionCallback(position) {
  // Assigning coords object for easier access.
  const coords = position.coords;

  // Position of the longitude .
  const longitude = coords.longitude;

  // Position of the latitude.
  const latitude = coords.latitude;

  // Accuracy of latitude & longitude in meters.
  const accuracy = coords.accuracy;

  // Altitude in meters, relative to sea level.
  const altitude = coords.altitude;

  // Accuracy of the altitude in meters. Value can be null.
  const altitudeAccuracy = coords.altitudeAccuracy;

  // Direction towards which the device is facing. This value specified
  // in degrees clockwise from North. Value can be null.
  const heading = coords.heading;

  // The velocity of the device in m/s. Value can be null.
  const speed = coords.speed;

  // The time at which the location was retrieved.
  const time = position.timestamp;
}
Enter fullscreen mode Exit fullscreen mode

所有值都是该double类型。

错误回调

function errorCallback(err) {
  let msg;
  switch (err.code) {
    case err.PERMISSION_DENIED:
        msg = "User denied the request for Geolocation.";
        break;
    case err.POSITION_UNAVAILABLE:
        msg = "Location information is unavailable.";
        break;
    case err.TIMEOUT:
        msg = "The request to get user location timed out.";
        break;
    case err.UNKNOWN_ERROR:
        msg = "An unknown error occurred.";
        break;
  }
}
Enter fullscreen mode Exit fullscreen mode

我认为这个函数非常直观。它只是将错误代码与错误类型进行比较,然后我们就可以以任何方式处理它。

实时位置🌎

要追踪设备的实时位置,我们可以调用watchPosition方法。此方法采用与 相同的参数getCurrentPosition。当设备位置发生变化时,该方法会将更新后的当前位置传递positionpositionCallback;如果error,则将error对象传递给errorCallback

const id = window.navigator.geolocation.watchPosition(
   positionCallback,
   errorCallback
);
Enter fullscreen mode Exit fullscreen mode
  • watchPosition方法返回一个id我们可以使用它来停止跟踪。

停止追踪🛑

要停止追踪实时位置,我们可以调用该clearWatch方法。该方法需要id一个参数。

window.navigator.geolocation.clearWatch(id);
Enter fullscreen mode Exit fullscreen mode

示例✨

查看GitHub repo中的示例代码。

在这里尝试一下

Mobile devices will give more accuracy.


最初发表于blog.bibekkakati.me


感谢您的阅读🙏

如果您喜欢这篇文章或觉得它有帮助,请点赞👍

欢迎随时联系👋

Twitter | Instagram | LinkedIn


如果你喜欢我的作品并想支持它,可以在这里留言。我会非常感激。



文章来源:https://dev.to/bibekkakati/track-user-s-location-on-your-website-58e0
PREV
Dev.to 完美地展示了如何开发基于内容的 Web 应用程序
NEXT
JavaScript 中的系统颜色主题检查