<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>位置权限示例</title>
</head>
<body>
<button id="getLocationButton">获取当前位置</button>
<div id="locationDisplay"></div>
<script>
document.getElementById('getLocationButton').addEventListener('click', function() {
// 检查浏览器是否支持 Geolocation API
if (navigator.geolocation) {
// 请求用户的位置权限
navigator.geolocation.getCurrentPosition(
function(position) {
// 用户同意提供位置信息
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
document.getElementById('locationDisplay').innerText =
`纬度: ${latitude}, 经度: ${longitude}`;
},
function(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;
}
}
);
} else {
alert("此浏览器不支持地理位置服务。");
}
});
</script>
</body>
</html>
完成效果如下:

















