用 浏览器自带的 navigator.geolocation.getCurrentPosition 获取定位权限时会报错;因为需要满足两个条件:
- 你的项目部署环境必须是https的地址;也就是说你必须有个公网服务器
- 必须用你的手机浏览器打开, 比如你在微信内嵌的浏览器打开,就没法弹出授权的框框
以下是一个小demo 可以部署试试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Geolocation Example</title>
</head>
<body>
<button id="getLocation">获取位置</button>
<div id="location">测试位置</div>
</body>
</html>
<script>
document.getElementById('getLocation').addEventListener('click', function () {
if ("geolocation" in navigator) {
alert(333);
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert(111);
document.getElementById('location').innerHTML = "Geolocation is not supported by this browser.";
}
});
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
alert(`Latitude: ${latitude}, Longitude: ${longitude}`);
document.getElementById('location').innerHTML = `Latitude: ${latitude}, Longitude: ${longitude}`;
}
function error() {
alert(222);
document.getElementById('location').innerHTML = "Unable to retrieve your location.";
}
</script>