navigator.geolocation.getCurrentPosition 是入口:成功回调拿到 coords.latitude(纬度)、longitude(经度)、accuracy(精度米数),失败回调返回错误码(1 拒绝授权、2 位置不可用、3 超时)。这是异步 API,且必须在 HTTPS 环境下才能调用。
watchPosition 可以持续监听位置变化,适合做导航轨迹,不用了要调 clearWatch 注销。拿到的只是经纬度,展示给用户还要配合地图 SDK 或逆地理编码服务。请注意定位属于敏感权限,不授权就拒绝,不要反复弹窗骚扰用户。
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function (pos) { console.log('纬度:', pos.coords.latitude); console.log('经度:', pos.coords.longitude); console.log('精度(米):', pos.coords.accuracy); }, function (err) { console.log('定位失败,错误码:', err.code, '原因:', err.message); }, { enableHighAccuracy: true, timeout: 5000 } ); } else { console.log('当前浏览器不支持地理定位'); }