navigator.geolocation.getCurrentPosition回调在Firefox 10上不起作用

时间:2012-02-09 17:23:36

标签: html5 firefox geolocation

我正在构建一个使用Geolocation API的应用。我似乎无法在Firefox 10上使用一段非常简单的代码。以下是代码:

    window.onload = function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                alert('it works');
            }, function(error) {
                alert('Error occurred. Error code: ' + error.code);         
            });
        }else{
            alert('no geolocation support');
        }
    };

所以,例如,在Chrome中,在运行页面后,我会被问到是否要分享我的位置,点击“是”后,它会提醒我“它有效”。现在在Firefox 10中,它会让我分享我的位置,点击分享后它什么也没做......我一直试图让回调运行任何类型的代码,但没有运气。这是Firefox的错误还是我做错了什么?我在这里有一个代码示例用于测试:http://dev-hub.com/geolocation.html

编辑--- 我的操作系统是Windows 7 64位

2 个答案:

答案 0 :(得分:19)

好吧我发现问题确实是Firefox,并且它在所有平台上都无法可靠或同等地运行。查看http://dev.w3.org/geo/api/spec-source.html我找到了以下选项:

    window.onload = function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                alert('it works');
            }, function(error) {
                alert('Error occurred. Error code: ' + error.code);         
            },{timeout:5000});
        }else{
            alert('no geolocation support');
        }
    };

正如你在这里看到的,超时:5000已被添加,这意味着如果由于某种原因浏览器需要超过5000毫秒(5秒)然后抛出超时错误(这是错误代码3)。所以现在每当Firefox不工作时它至少运行错误回调,我收到一条警告消息“发生错误。错误代码:3”。

显然,超时的默认值是无限的,所以它永远不会超时...... Chrome是100%可靠但Firefox在我的机器上大约10%可靠,这是非常令人失望的。在我的另一台运行Windows XP且位于同一网络上的计算机上,Firefox似乎100%可靠。

答案 1 :(得分:0)

我为你做了这个例子:

if(!navigator.geolocation){
alert('El Navegador no soporta GeoLocalización');
}

function doGeo( position ) 
{
    var coords = position.coords.latitude + '+' + position.coords.longitude;
    var url = 'https://maps.google.es/?q=' + coords;
    $( "#lat" ).html("Latitud: " + position.coords.latitude );
    $( "#lon" ).html("Longitud: " + position.coords.longitude );
    $( "#acc" ).html("Precisión: " + position.coords.accuracy );
    $( "#alt" ).html("Altitud: " + position.coords.speed );        
    var link = '<a class="btn btn-primary" href="' + url + '" target="_blank">Ir a la     Ubicación en Google Maps</a>';
    $(link).appendTo('#GoogleMaps');
}

function lost()
{
    alert('Algo salió mal, Intentelo más tarde...');
};
navigator.geolocation.watchPosition(doGeo, lost, {maximumAge:0,enableHighAccuracy:true}          );

http://jsfiddle.net/aA2zv/35/

希望它有所帮助!