参考错误地理位置

Reference error geolocation

本文关键字:地理位置 错误 参考      更新时间:2023-09-26

我试图在javascript中使用地理定位。然而,在我的控制台上,我看到一个错误是:ReferenceError: success is not defined。因此,我无法执行我的代码无法执行函数的其余部分。下面是我的实现:

function clicked(){
        console.log("inside clicked");
        if($("#checkbox-h-2j").prop('checked')){
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(success,error);
            }
            else{
                document.getElementById("hello").innerHTML = "Not supported";
            }
            function success(position){
                    lat = position.coords.latitude;
                    lng = position.coords.longitude;
                    document.getElementById("hello").innerHTML = "lat :"+lat+"<br>long :"+lng;
            }
            function error(err){
                    document.getElementById("hello").innerHTML = "Error Code: "+error.code;
                    if(err.code == 1){
                        document.getElementById("hello").innerHTML = "Access denied";
                        }
                    if(err.code == 2){
                        document.getElementById("hello").innerHTML = "Position unavailable";
                    }
            }
}}

是否参考错误在第08行,即

navigator.geolocation.getCurrentPosition(success,error);

如果是这样,那么问题可能是当你使用success时,这个函数在被定义之前就被使用了,因此它会停止进一步的执行,在使用它之前尝试定义函数,然后它会工作。

我假设你在Firefox中得到错误,但在Chrome中没有。下面是一个简单的例子:

if (true) {
    foo();
    function foo() {
        console.log('bar');
    }
}
问题是您在中使用了函数声明实际上是一个语法错误,但是浏览器会选择不同的方式来处理这个问题。

Chrome将提升函数声明(像任何其他函数声明),因此结果是

function foo() {
   console.log('bar');
}
if (true) {
    foo();
}

。无论条件的结果如何,函数都将始终被定义。

Firefox会将该声明视为函数表达式,而不是像

那样
if (true) {
    foo();
    var foo = function foo() {
        console.log('bar');
    }
}

在这种情况下,您将尝试在定义函数之前调用它,这当然是行不通的。

注意:这不是Firefox真正的工作方式,因为上面的例子会生成一个类型错误,而不是引用错误,但通常情况下它是这样工作的:

有关此问题的更多信息,请参阅MDN文档


<

解决方案/strong>:

在块内,总是使用函数表达式,而不是函数声明。函数表达式必须在使用之前定义。也就是说,你的代码变成了像

这样的东西
if($("#checkbox-h-2j").prop('checked')){
    var success = function() { ... };
    var error = function() { ... };
    navigator.geolocation.getCurrentPosition(success,error);
}