2014-04-15 126 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