Table of Contents
GPS 位置获取
HTML5 提供了 navigator.geolocation 接口,可以在浏览器中请求用户的地理位置。调用时浏览器会弹出权限确认,用户允许后才能读取经纬度等信息。
需要注意:现代浏览器通常要求页面运行在 HTTPS 环境,或者在本地开发环境 localhost 下测试。否则即使代码正确,也可能无法获取位置。
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
} else {
alert("您的浏览器不支持使用 HTML5 来获取地理位置服务");
}
// 定位数据获取成功响应
function onSuccess(position) {
alert('纬度: ' + position.coords.latitude + '\n' +
'经度: ' + position.coords.longitude + '\n' +
'海拔: ' + position.coords.altitude + '\n' +
'水平精度: ' + position.coords.accuracy + '\n' +
'垂直精度: ' + position.coords.altitudeAccuracy);
}
// 定位数据获取失败响应
function onError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("您拒绝了获取地理位置的请求");
break;
case error.POSITION_UNAVAILABLE:
alert("位置信息不可用");
break;
case error.TIMEOUT:
alert("请求您的地理位置超时");
break;
case error.UNKNOWN_ERROR:
alert("未知错误");
break;
}
}
</script>
字段说明
position.coords.latitude:纬度。position.coords.longitude:经度。position.coords.altitude:海拔。如果设备或浏览器无法提供,可能为null。position.coords.accuracy:水平精度,单位通常是米。position.coords.altitudeAccuracy:垂直精度。如果无法提供,可能为null。
可复现检查
把上面的代码保存为一个 HTML 文件,在支持定位权限的浏览器中打开。若浏览器阻止定位请求,请先确认页面是否通过 HTTPS 访问,并检查浏览器和系统的定位权限设置。
