首页 > 解决方案 > 为什么不触发回调函数?

问题描述

我有这个功能,指示是否在浏览器上启用了地理定位:

function geolocationInfo() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    }
    else {
        return "Geolocation not works in this browser";
    }
}

  function success(position) {
        var crd = position.coords;

        console.log('Ваше текущее метоположение:');
        console.log(`Широта: ${crd.latitude}`);
        console.log(`Долгота: ${crd.longitude}`);
        console.log(`Плюс-минус ${crd.accuracy} метров.`);
    }

    function error(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                return "Geolocation disabled";
            case error.POSITION_UNAVAILABLE:
                return "GeoLocation is not available";
            case error.TIMEOUT:
                return "Time is ends";
            case error.UNKNOWN_ERROR:
                return "error.";               
        }
    }

问题是没有触发回调函数。

知道为什么不触发回调(成功和错误)吗?

标签: javascriptgeolocationgpslocationgis

解决方案


如果您尝试在 chrome 的控制台中使用您的代码,并运行您的函数

geolocationInfo()

然后在浏览器中检查具有权限的弹出窗口,因为用户必须允许网页查看该位置

Chrome 中的示例


推荐阅读