使用 Geolocation API
Geolocation API 用于获取用户的当前位置,以便例如可以使用地图 API 来显示他们的位置。本文档解释了如何使用它的基础知识。
Geolocation 对象
可以通过 navigator.geolocation 对象访问 Geolocation API。
如果该对象存在,则表示地理定位服务可用。您可以通过以下方式测试地理定位是否存在:
if ("geolocation" in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}
获取当前位置
要获取用户的当前位置,可以调用 getCurrentPosition() 方法。这会启动一个异步请求来检测用户的位置,并查询定位硬件以获取最新信息。当位置确定后,将执行定义的 callback 函数。您可以选择提供第二个 callback 函数,以在发生错误时执行。第三个可选参数是一个 options 对象,您可以在其中设置返回位置的最大年龄、请求等待时间以及是否需要高精度位置。
注意:默认情况下,getCurrentPosition() 尝试以低精度结果尽快响应。如果您需要快速响应而不关心精度,这非常有用。例如,带有 GPS 的设备可能需要一分钟或更长时间才能获得 GPS 信号,因此 getCurrentPosition() 可能会返回不太精确的数据(IP 地址定位或 Wi-Fi)。
navigator.geolocation.getCurrentPosition((position) => {
doSomething(position.coords.latitude, position.coords.longitude);
});
上面的示例将在获取到位置信息后执行 doSomething() 函数。
监视当前位置
如果位置数据发生变化(由于设备移动或收到更精确的地理信息),您可以设置一个 callback 函数,该函数会在收到更新的位置信息时被调用。这可以通过 watchPosition() 函数来实现,该函数具有与 getCurrentPosition() 相同的输入参数。callback 函数会多次调用,允许浏览器在您移动时更新您的位置,或者在使用不同技术进行地理定位时提供更精确的位置。错误 callback 函数(与 getCurrentPosition() 一样可选)也可以被重复调用。
注意:您可以直接使用 watchPosition() 而无需先调用 getCurrentPosition()。
const watchID = navigator.geolocation.watchPosition((position) => {
doSomething(position.coords.latitude, position.coords.longitude);
});
watchPosition() 方法返回一个 ID 号,可用于唯一标识请求的位置监视器;您将此值与 clearWatch() 方法结合使用,以停止监视用户的位置。
navigator.geolocation.clearWatch(watchID);
微调响应
getCurrentPosition() 和 watchPosition() 都接受一个成功 callback、一个可选的错误 callback 和一个可选的 options 对象。
此对象允许您指定是否启用高精度、返回位置值的最大年龄(在此年龄之前将被缓存并重用,如果再次请求相同位置;之后浏览器将请求新的位置数据)以及一个超时值,该值决定了在超时之前浏览器应该尝试获取位置数据多长时间。
对 watchPosition 的调用可能看起来像这样:
function success(position) {
doSomething(position.coords.latitude, position.coords.longitude);
}
function error() {
alert("Sorry, no position available.");
}
const options = {
enableHighAccuracy: true,
maximumAge: 30000,
timeout: 27000,
};
const watchID = navigator.geolocation.watchPosition(success, error, options);
描述位置
用户的当前位置由 GeolocationPosition 对象实例描述,该实例本身包含一个 GeolocationCoordinates 对象实例。
GeolocationPosition 实例仅包含两项:一个 coords 属性,其中包含 GeolocationCoordinates 实例;以及一个 timestamp 属性,其中包含获取位置数据时的时间戳,以毫秒为单位的 Unix 时间。
GeolocationCoordinates 实例包含许多属性,但您最常用的两个是 latitude 和 longitude,它们是您在地图上绘制位置所需的。因此,许多 Geolocation 成功 callback 函数看起来非常简单:
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// Do something with your latitude and longitude
}
但是,您还可以从 GeolocationCoordinates 对象中获取许多其他信息,包括海拔、速度、设备朝向以及海拔、经度和纬度数据的精度。
处理错误
如果调用 getCurrentPosition() 或 watchPosition() 时提供了错误 callback 函数,它将接受一个 GeolocationPositionError 对象实例作为其第一个参数。此对象类型包含两个属性:一个 code,指示返回的错误类型;以及一个人类可读的 message,描述了错误代码的含义。
您可以这样使用它:
function errorCallback(error) {
alert(`ERROR(${error.code}): ${error.message}`);
}
示例
在下面的示例中,Geolocation API 用于获取用户的纬度和经度。如果成功,则可用链接将填充一个 openstreetmap.org URL,该 URL 将显示他们的位置。
HTML
<button id="find-me">Show my location</button><br />
<p id="status"></p>
<a id="map-link" target="_blank"></a>
JavaScript
function geoFindMe() {
const status = document.querySelector("#status");
const mapLink = document.querySelector("#map-link");
mapLink.href = "";
mapLink.textContent = "";
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.textContent = "";
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = "Unable to retrieve your location";
}
if (!navigator.geolocation) {
status.textContent = "Geolocation is not supported by your browser";
} else {
status.textContent = "Locating…";
navigator.geolocation.getCurrentPosition(success, error);
}
}
document.querySelector("#find-me").addEventListener("click", geoFindMe);