2009-12-22 105 views
22

我需要在50m以內決定一個人的位置。我不知道我是否應該使用navigator.location.watchPostion()或者一遍又一遍地打電話getCurrentPostion()watchPostion()是做我想要的正確W3C API,但實際上,它似乎是矯枉過正。watchPosition()與getCurrentPosition()與setTimeout的

這裏是我的代碼:

var map = null; 
var marker = null; 
var layer = null; 

function locFn(pos) { 

    var lat = pos.coords.latitude; 
    var lon = pos.coords.longitude; 

    $("#hlat").val(lat); 
    $("#hlong").val(lon); 

    document.getElementById("lnkMap").href = 
    "http://maps.google.com/[email protected]" + lat 
    + "," + lon + "&z=18&t=h"; 

    var point = new GLatLng(lat, lon); 

    if (pos.coords.accuracy < 100) { 
    map.setCenter(point, 18); 

    if (marker != null) { 
     marker.setLatLng(point); 
    } 
    else { 
     var ico = new GIcon(); 
     ico.image = "img/Blue-Dot.png"; 
     ico.iconSize = new GSize(22, 22); 
     ico.iconAnchor = new GPoint(11, 11); 
     marker = new GMarker(point, { icon: ico }); 
     layer = map.addOverlay(marker, { title: "You are here." }); 
    } 
    } 
    else if (pos.coords.accuracy > 2000) { 
    if (marker != null) { marker.setLatLng(point); } 
    map.setCenter(point, 15); 
    } 
    else if (pos.coords.accuracy > 900) { 
    if (marker != null) { marker.setLatLng(point); } 
    map.setCenter(point, 16); 
    } 
    else if (pos.coords.accuracy > 100) { 
    if (marker != null) { marker.setLatLng(point); } 
    map.setCenter(point, 17); 
    } 
} 

function locFail() { 
    //alert("Failed to retrieve location."); 
} 

var watchID = null; 

function processPoints() { 
    map = new GMap2(document.getElementById("map_canvas"), 
        { mapTypes: [G_HYBRID_MAP] }); 
    try { 
    watchID = navigator.geolocation.watchPosition(locFn, locFail, 
      { enableHighAccuracy: true }); 
    } 
    catch(err) { /* desktop?*/ } 
} 
$(function(){processPoints();}); 

我注意到watchPostion()似乎最終導致更高的準確度(過了一會兒),但我想知道,如果位置變化如此之快,這導致了很多事情被下載到我的地圖畫布,用恆定的HTTP請求是很快就過期,由新進來代替。當我使用watchPosition(),它的頁面加載之前需要一段時間。

+0

在那裏,你可以發佈您的解決方案的完整的HTML +的Javascript的一個例子什麼辦法?包括監聽器和enableContinuousZoom()調用?我不熟悉的GMap2等我有逆向工程...但它可能挽救別人在我的鞋一定的工作有一天... – ftrotter 2011-04-11 06:28:08

+0

檢查,我回答了下面山姆評論。 – devlord 2011-05-26 22:29:32

+0

望着文檔,似乎有什麼東西GetCurrentPosition(這立刻運行成功處理)和WatchPosition的極端(其目的是全程運行時間,用戶在頁面上)之間失蹤。我也喜歡上了GetCurrentPosition所說的「門檻精確」選項 - 它等待這個精度,或超時。除非其他人已經使用WatchPosition創建了這個,否則我想我現在會這樣做。 – 2011-06-07 12:03:11

回答

17

經過一番認真的測試,我已經驗證watchPosition()將遠遠超過getCurrentPostion(更迅速)一遍又一遍給你一個準確的位置。當使用watchPostion()時,如果每次設備更新您的位置時都反覆重新繪製地圖,那麼地圖的表現會很差。爲了解決這個問題,我添加了一個監聽器tilesloaded事件,這使得如果沒有已經開始嘗試在地圖上繪製一個線程我只繪製地圖。一旦用戶對確定的位置感到滿意,我將清除手錶。就電池消耗和準確性而言,這將使我獲得兩全其美的好處。

12

每次你打電話getCurrentLocation的GPS是紡起來,這需要一些時間。 如果調用watchPosition,等待,直到你得到一定的精度,然後刪除你的手錶,你將有更好的結果,沒有一個恆定的手錶的開銷。