HTML5 geolocation 定位获取权限 注意事项

用 浏览器自带的 navigator.geolocation.getCurrentPosition 获取定位权限时会报错;因为需要满足两个条件:

  1. 你的项目部署环境必须是https的地址;也就是说你必须有个公网服务器
  2. 必须用你的手机浏览器打开, 比如你在微信内嵌的浏览器打开,就没法弹出授权的框框

以下是一个小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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。