JavaScript通过Geolocation API获取用户位置,需用户授权且仅限安全上下文;支持getCurrentPosition()和watchPosition(),注意兼容性、精度限制及国内浏览器降级方案。
JavaScript 通过浏览器提供的 Geolocation API 获取用户地理位置,无需第三方库,但需用户明确授权,且仅在安全上下文(https 或 localhost)中可用。
使用 navigator.geolocation 判断兼容性,避免在不支持的环境中报错:
navigator 对象)调用 getCurrentPosition() 获取一次当前位置,传入成功与失败回调:
position 对象,含 coords.latitude、coords.longitude、coords.accuracy(单位:米)等字段error 对象,error.code 可为 1(用户拒绝)、2(位置不可用)、3(超时){ enableHighAccuracy: true, timeout: 5000, maximumAge: 60000 }
使用 watchPosition() 持续跟踪位置变动,返回一个唯一 watchId,可用于后续停止监听:
合地图应用、运动轨迹记录等场景navigator.geolocation.clearWatch(watchId) 释放资源maximumAge 和 enableHighAccuracy
实际使用中需兼顾体验与合规性:
enableHighAccuracy: true 仅作提示,不保证结果更准