代码之家  ›  专栏  ›  技术社区  ›  devlord

watchPosition()与getCurrentPosition()以及setTimeout

  •  24
  • devlord  · 技术社区  · 16 年前

    navigator.location.watchPostion() 还是打电话 getCurrentPostion() 一次又一次 watchPostion()

    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();});
    

    我注意到了 值班 watchPosition() ,页面加载前确实需要一段时间。

    2 回复  |  直到 8 年前
        1
  •  22
  •   devlord    16 年前

    经过一些认真的测试,我反复验证了watchPosition()将比GetCurrentPosition()更快地为您提供准确的位置。使用watchposition()时,如果每次设备更新您的位置时都反复重新绘制地图,则地图会表现不佳。为了解决这个问题,我在tilesloaded事件中添加了一个监听器,这只允许我在没有线程试图在地图上绘制的情况下重新绘制地图。一旦用户对确定的位置满意,我将清除手表。就电池消耗和准确性而言,这将使我获得两个方面的最佳效果。

        2
  •  12
  •   Jesse MacFadyen    16 年前

    如果您调用watchPosition并等待获得一定的精度,然后卸下手表,您将获得更好的结果,而不需要固定手表的开销。

    推荐文章