2014-04-15 127 views
-1

我已经在我的项目中实现了HTML地理位置功能,但是我注意到它并不总是可靠的。HTML5地理位置超时

如何在x秒后添加回退到超时并显示错误?

这里是我的代码:

function getLocation() 
{ 
    if (navigator.geolocation) 
    { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } 
    else{x.innerHTML = "Geolocation is not supported by this browser, please manually enter your postcode above";} 

    ); 
} 

function showPosition(position) 
{ 
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
} 
+1

可能的重复http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt – mccainz

回答

0

,你可能会最好添加错误回调和选项对象。

navigator.geolocation.getCurrentPosition(
    currentPositionSuccess, 
    currentPositionFail, 
    // maximumAge refers to the age of the location data in cache, 
    // setting it to infinity guarantees you'll get a cached version. 
    // Setting it to 0 forces the device to retrieve the position. 
    // http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt 
    { maximumAge: 15000, 
    timeout: 30000, 
    enableHighAccuracy: false 
    } 
); 

文章@Brian Mains指的是好的。

我必须在我的(三星)Android 4上启用高精度定位才能正常工作。 (也许省电定位工作为好。)

主屏幕>菜单键>设置>更多>位置(开启)> 模式(它可能看起来像一个标题,但它不是)>高准确性

+0

我注意到你已经关闭了HighAccuracy的参数,如果设备不支持高精度不会回落到“正常”精度? – Imran

+0

我的用例获得了从当前位置到另一个地理位置的距离和驾驶时间。我不觉得高精度是显着的。 – JohnSz

+1

移动设备上的高精度使用GPS。有些报道通常需要10-30秒才能获得。我感觉用户不会感激10-30秒的等待,再加上取整的结果会吃掉任何额外的准确度。基本上,这取决于你的用例。 – JohnSz

1

你可以给它一个回调,需要一个方法来处理错误:

navigator.geolocation.getCurrentPosition(
    show_map, handle_error); 

function handle_error(err) { 
    if (err.code == 1) { 
    // user said no! 
    } 
} 

来自http://diveintohtml5.info/geolocation.html