HTML 5 Geolocation watchPosition

时间:2011-12-02 15:14:31

标签: javascript html5 geolocation

我正在尝试设置我的代码,以便在Android手机或平板电脑上找到最准确的位置。由于getCurrentPosition没有足够的时间让GPS找到位置,我使用的是watchPosition。这很好但我需要允许用户停止这个watchPostion所以我正在使用clearWatch函数。这个clearWatch功能适用于我的Android手机2.2.2版本,但不适用于Android平板电脑3.2.1版本。我的另一个问题是在我的Android手机上,一旦我停止/清除手表,我再次尝试找到我的位置,我的手机振动,浏览器关闭。这是什么问题?我也在其他手机上试过这个并且遇到了同样的问题。如果有人有任何建议我会非常感激。以下是我正在使用的代码。

//function to locate using GPS
function ShowMyLocation(){
  if (navigator.geolocation) {
    ShowProgressIndicator('map');
    watchID = navigator.geolocation.watchPosition(function(position){
      var mapPoint = esri.geometry.geographicToWebMercator(new esri.geometry.Point(position.coords.longitude, position.coords.latitude, new esri.SpatialReference({
        wkid: 4326
      })));
      var graphicCollection = esri.geometry.geographicToWebMercator(new esri.geometry.Multipoint(new esri.SpatialReference({
        wkid: 4326
      })));
      graphicCollection.addPoint(mapPoint);
      geometryService.project([graphicCollection], map.spatialReference, function(newPointCollection){
        HideProgressIndicator();
        if (!map.getLayer(baseMapLayerCollection[0].Key).fullExtent.contains(mapPoint)) {
          alert('Data not available for the specified address.');
          return;
        }
        mapPoint = newPointCollection[0].getPoint(0);
        AddServiceRequest(mapPoint);
      });
    }, function(error){
      HideProgressIndicator();
      switch (error.code) {
        case error.TIMEOUT:
                alert('Timeout');
                break;
        case error.POSITION_UNAVAILABLE:
          alert('Position unavailable');
          break;
        case error.PERMISSION_DENIED:
          alert('Permission denied');
          break;
        case error.UNKNOWN_ERROR:
          alert('Unknown error');
          break;
      }
    }, {
      timeout: 5000,
      maximumAge: 90000,
      enableHighAccuracy: true      
    });

  }
}
 function clearWatch(){
   // Cancel the updates when the user clicks a button.
  if (watchID > 0) {
    navigator.geolocation.clearWatch();
    alert("Stop tracking location");
  }
}

1 个答案:

答案 0 :(得分:3)

您的语法不正确。 clearWatch获取要取消哪个监视ID的参数。

在您的情况下,您应该clearWatch(watchID),而不是clearWatch()