在前端开发中,通过BOM的Geolocation API可以获取用户的GPS位置信息,这是浏览器原生提供的定位能力,无需引入额外依赖,适用于各类需要位置服务的Web场景。

Geolocation API基础说明
BOM的navigator.geolocation对象是获取位置信息的核心入口,它提供了三个主要方法:getCurrentPosition用于获取当前位置,watchPosition用于持续监听位置变化,clearWatch用于停止位置监听。需要注意的是,该API仅在安全上下文下可用,也就是页面协议必须是HTTPS,本地开发时使用localhost或者127.0.0.1也可以正常调用。
获取单次GPS位置
获取单次位置是最常用的场景,调用getCurrentPosition方法即可实现,该方法接收三个参数:成功回调、失败回调、可选的配置参数。
基础使用示例
以下是一个简单的获取当前GPS位置的代码:
// 检查浏览器是否支持Geolocation API
if ('geolocation' in navigator) {
// 调用获取当前位置的方法
navigator.geolocation.getCurrentPosition(
// 成功回调,接收位置对象
function successCallback(position) {
// 位置对象包含坐标信息
const latitude = position.coords.latitude; // 纬度
const longitude = position.coords.longitude; // 经度
const accuracy = position.coords.accuracy; // 位置精度,单位米
console.log('获取到的GPS位置:');
console.log('纬度:' + latitude);
console.log('经度:' + longitude);
console.log('精度:' + accuracy + '米');
},
// 失败回调,接收错误对象
function errorCallback(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.log('用户拒绝了定位权限申请');
break;
case error.POSITION_UNAVAILABLE:
console.log('无法获取位置信息');
break;
case error.TIMEOUT:
console.log('获取位置超时');
break;
default:
console.log('发生未知错误');
}
},
// 可选配置参数
{
enableHighAccuracy: true, // 是否尝试获取高精度位置,会消耗更多电量
timeout: 10000, // 获取位置的超时时间,单位毫秒
maximumAge: 0 // 缓存位置的最大时长,0表示不使用缓存
}
);
} else {
console.log('当前浏览器不支持Geolocation API');
}
持续监听GPS位置变化
如果需要实时获取用户的位置变化,比如运动轨迹记录场景,可以使用watchPosition方法,它的参数和getCurrentPosition一致,会返回一个监听ID,后续可以通过clearWatch停止监听。
持续监听示例
以下是持续监听位置变化的代码实现:
let watchId = null;
// 开始监听位置变化
function startWatchPosition() {
if ('geolocation' in navigator) {
watchId = navigator.geolocation.watchPosition(
function successCallback(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log('最新位置 纬度:' + latitude + ',经度:' + longitude);
},
function errorCallback(error) {
console.log('监听位置失败:' + error.message);
},
{
enableHighAccuracy: true,
timeout: 5000
}
);
}
}
// 停止监听位置变化
function stopWatchPosition() {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
console.log('已停止位置监听');
}
}
常见问题与注意事项
- 权限申请:首次调用定位接口时,浏览器会弹出权限申请弹窗,用户拒绝后再次调用会直接触发失败回调,需要引导用户手动开启权限。
- 精度问题:
enableHighAccuracy设置为true时,会优先使用GPS模块获取位置,精度更高但耗电更多,移动端设备上效果更明显,PC端可能还是基于IP定位。 - 兼容性:大部分现代浏览器都支持该API,如果需要兼容非常旧的浏览器,可以在调用前先做支持性判断,避免代码报错。
- 安全限制:非安全上下文下调用该API会直接失败,线上环境必须使用HTTPS协议部署页面。
位置信息返回字段说明
position.coords对象除了纬度和经度外,还包含其他有用的字段,具体说明如下:
| 字段名 | 说明 |
|---|---|
| latitude | 纬度,单位为度,范围-90到90 |
| longitude | 经度,单位为度,范围-180到180 |
| accuracy | 位置精度,单位为米,数值越小精度越高 |
| altitude | 海拔高度,单位为米,如果不可用则返回null |
| altitudeAccuracy | 海拔精度,单位为米,如果不可用则返回null |
| heading | 运动方向,单位为度,顺时针从正北开始计算,如果不可用则返回null |
| speed | 运动速度,单位为米每秒,如果不可用则返回null |
BOMGeolocation_API获取GPS位置前端定位修改时间:2026-07-13 21:18:26