【问题标题】:Can someone show me how to use the watch position () function with getCurrentPosition?有人可以告诉我如何使用 getCurrentPosition 的 watch position () 函数吗?
【发布时间】:2016-04-12 16:32:00
【问题描述】:

以下是我使用的查找用户位置的代码。

if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
        me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
        infoWindow.setPosition(me);
          infoWindow.setContent('Location found.');
        },

    function(error) {
        handleLocationError(true, infoWindow, map.getCenter());
    });
    else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
      }
      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
      infoWindow.setPosition(me);
      infoWindow.setContent(browserHasGeolocation ?
                            'Error: The Geolocation service failed.' :
                            'Error: Your browser doesn\'t support geolocation.');
    } 

我已经尝试在下面添加监视位置功能但它不起作用,我不确定它是如何工作的。

var watchID = navigator.geolocation.watchPosition(function(position) {
  (position.coords.latitude, position.coords.longitude);
});

 function getLocationUpdate(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
            }

            else{
               alert("Sorry, browser does not support geolocation!");
            }

如果有人可以帮助我在地图上查看用户的位置,我将不胜感激!非常感谢。

【问题讨论】:

    标签: javascript jquery api google-maps


    【解决方案1】:

    watchPosition() 方法用于注册一个处理函数,该处理函数将在每次设备位置发生变化时自动调用。您还可以选择指定错误处理回调函数。

    此方法返回一个监视 ID 值,然后可用于取消注册处理程序,方法是将其传递给 clearWatch() 方法。

    要获取用户的当前位置,可以调用getCurrentPosition()方法。这会发起一个异步请求来检测用户的位置,并查询定位硬件以获取最新信息。当位置确定后,执行定义的回调函数。如果发生错误,您可以选择提供要执行的第二个回调函数。第三个可选参数是一个选项对象,您可以在其中设置返回的位置的最长期限、等待请求的时间以及是否需要高精度的位置。

    如果位置数据发生变化(通过设备移动或到达更准确的地理信息),您可以设置一个回调函数,使用该更新的位置信息调用该函数。这是使用watchPosition() 函数完成的,该函数具有与getCurrentPosition() 相同的输入参数。回调函数被多次调用,允许浏览器在您移动时更新您的位置,或者在使用不同技术对您进行地理定位时提供更准确的位置。错误回调函数,和getCurrentPosition()一样是可选的,可以重复调用。

    更多信息请查看documentation

    还要检查这个SO question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-09
      • 2012-09-16
      • 2021-11-16
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      相关资源
      最近更新 更多