watchPosition()vs getCurrentPosition()with setTimeout

dev*_*ord 24 javascript iphone google-maps geolocation iphone-web-app

我需要在50米内确定一个人的位置.我想知道我是应该一次又一次地使用navigator.location.watchPostion()或打电话getCurrentPostion(). watchPostion()是正确的W3C API,用于做我想要的,但实际上,它似乎是矫枉过正.

这是我的代码:

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/maps?q=My+Loc@" + 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();});
Run Code Online (Sandbox Code Playgroud)

我注意到watchPostion()似乎最终会导致更准确(一段时间后),但我想知道位置变化是否如此之快以至于导致很多东西被下载到我的地图画布中,并且很快就会有一些http请求过时了,取而代之的是新的.当我使用watchPosition()时,在页面加载之前需要一段时间.

dev*_*ord 20

经过一些严肃的测试,我已经验证了watchPosition()会比getCurrentPostion()一遍又一遍地给你一个准确的位置.使用watchPostion()时,如果每次设备更新您的位置时反复重绘地图,地图都会表现不佳.为了解决这个问题,我在tilesloaded事件中添加了一个监听器,如果还没有线程试图在地图上绘制,那么我只允许重绘地图.一旦用户对确定的位置感到满意,我将清除手表.就电池消耗和准确性而言,这将使我获得两全其美.


小智 12

每次调用getCurrentLocation时,gps都会旋转,这需要一些时间.如果您调用watchPosition并等到获得一定的准确度,那么移除您的手表将获得更好的结果,而不会产生持续监视的开销.