如何在JS中获取用户位置

993 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情

什么是地理位置API?

JavaScript地理位置API提供了对与用户设备关联的地理位置数据的访问。这可以通过GPS、WIFI、IP地理位置等来确定。

为了保护用户的隐私,它请求允许找到设备。如果用户授予权限,你将获得对纬度、经度、海拔和速度等位置数据的访问权限。你还将获得所获取位置数据的准确性以及获得位置的大致时间。

以下是地理位置的一些用途:

  • 显示用户在地图上的位置
  • 获取最新的本地信息
  • 显示用户附近的本地兴趣点(POI)
  • 启用逐向导航(GPS)
  • 跟踪车队或送货车辆
  • 用位置标记照片

如何使用地理位置API

你可以通过调用navigator.geolocation对象来访问地理位置API。它授予应用程序对设备位置的访问权限。

此对象提供了以下列出的处理设备位置的方法:

  1. getCurrentPosition:返回设备的当前位置。
  2. watchPosition:当设备位置发生变化时自动调用的处理程序功能。

这些方法有三个可能的论点:

  • 成功回电(必填)
  • 错误回调(可选)
  • 选项对象(可选)

如何通过getCurrentPosition()

You can use the getCurrentPosition method to get the user's current location. It sends an asynchronous request to the browser, asking for consent to share their location.

以下是获取用户位置的语法:

const successCallback = (position) => {
  console.log(position);
};

const errorCallback = (error) => {
  console.log(error);
};

navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

当你运行此操作时,你将在浏览器中看到一个请求权限的弹出窗口:

弹出窗口

点按“允许”,然后打开开发者控制台。你会看到,成功通话会返回两件事:

  1. GeolocationPosition.coords对象:表示设备计算这些属性的位置、高度和准确性。
  2. timestamp:表示获得位置的时间。
  3. 你应该在控制台中看到这样的东西:
GeolocationPosition {coords: GeolocationCoordinates, timestamp: 1662499816712}
    coords: GeolocationCoordinates
        accuracy: 7173.528443511279
        altitude: null
        altitudeAccuracy: null
        heading: null
        latitude: 6.5568768
        longitude: 3.3488896
        speed: null
        [[Prototype]]: GeolocationCoordinates
timestamp: 1662499816712

通过这个简单的请求,我们成功获得了位置。但这不是全部。我们还可以通过观察用户的位置来跟踪他们。

如何跟踪用户位置watchPosition()

watchPosition()方法允许应用程序持续跟踪用户,并随着他们位置的变化进行更新。它通过安装处理程序函数来做到这一点,每当用户的设备位置发生变化时,该函数都会自动调用。

以下是以下语法,其中id主要用于管理或引用该方法:

const id = navigator.geolocation.watchPosition(successCallback, errorCallback);

如何停止跟踪位置clearWatch()

我们使用clearWatch()方法来取消之前使用watchPosition安装的处理程序函数。

navigator.geolocation.clearWatch(id);

如何使用options对象

虽然options对象是可选的,但它提供了可以帮助你获得更准确结果的参数,例如:

const options = {
  enableHighAccuracy: true,
  timeout: 10000,
};

navigator.geolocation.getCurrentPosition(
  successCallback,
  errorCallback,
  options
);

在上面的代码中,我们在选项对象中指定了:

  • 响应应通过将enableHighAccuracy设置为true来提供更准确的位置。
  • 设备为了返回位置而允许的最大时间长度(以毫秒为单位)。在这种情况下,10秒。

总结

在本文中,我们了解了JavaScript地理位置API,如何使用它来获取用户的位置,以及使用watchPosition()方法跟踪用户。