js实现gps定位
使用浏览器Geolocation API获取GPS定位
浏览器提供的Geolocation API是最简单的实现方式,适用于移动端和桌面端浏览器环境。需要用户授权才能获取位置信息。

if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`纬度: ${latitude}, 经度: ${longitude}`);
},
(error) => {
console.error("获取位置失败:", error.message);
},
{
enableHighAccuracy: true, // 请求高精度定位
timeout: 5000, // 超时时间(毫秒)
maximumAge: 0 // 不接受缓存位置
}
);
} else {
console.error("浏览器不支持地理定位");
}
持续监听位置变化
对于需要实时追踪位置的场景,可以使用watchPosition方法代替getCurrentPosition:

const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log(`新位置: ${position.coords.latitude}, ${position.coords.longitude}`);
},
(error) => {
console.error("监听位置失败:", error.message);
}
);
// 需要停止监听时调用
// navigator.geolocation.clearWatch(watchId);
处理定位权限状态
现代浏览器要求地理位置API必须运行在安全上下文(HTTPS)中,HTTP环境下仅localhost可用:
navigator.permissions.query({name:'geolocation'}).then(result => {
if (result.state === 'granted') {
console.log("已授予定位权限");
} else if (result.state === 'prompt') {
console.log("等待用户授权");
} else if (result.state === 'denied') {
console.log("用户拒绝定位权限");
}
});
使用第三方地图服务API
对于需要更高精度或附加功能的场景,可以集成地图服务商的定位SDK:
// 以高德地图为例
const AMapLoader = {
load(key) {
return new Promise((resolve) => {
window.initAMap = () => resolve(window.AMap);
const script = document.createElement('script');
script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}&callback=initAMap`;
document.head.appendChild(script);
});
}
};
AMapLoader.load('YOUR_API_KEY').then(AMap => {
AMap.plugin('AMap.Geolocation', () => {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true,
timeout: 10000
});
geolocation.getCurrentPosition((status, result) => {
if (status === 'complete') {
console.log(result.position);
} else {
console.error(result.message);
}
});
});
});
注意事项
- 生产环境必须使用HTTPS协议,iOS 10+和Android现代浏览器都强制要求
- 精度受设备硬件、环境和用户设置影响,移动设备通常比桌面电脑更精确
- 部分浏览器会限制连续定位请求频率,避免过度调用API
- 用户可能拒绝权限请求,需要提供友好的回退方案
- 考虑隐私政策要求,明确告知用户位置数据的用途





