我有一个很简单的JS使用navigator。geolocation。getcurrentposition jammy。

$(document).ready(function(){
  $("#business-locate, #people-locate").click(function() {
    navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
  });

  navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

  function foundLocation(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var userLocation = lat + ', ' + lon;
    $("#business-current-location, #people-current-location").remove();
    $("#Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='business-current-location' id='business-current-location' value='"+userLocation+"' />");
    $("#people-Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='people-current-location' id='people-current-location' value='"+userLocation+"' />");
  }
  function noLocation() {
    $("#Near-Me").watermark("Could not find location");
    $("#people-Near-Me").watermark("Could not find location");
  }
})//end DocReady

基本上,这里发生的事情是我们得到当前位置,如果它得到了,两个“水印”被放置在两个字段中,表示“当前位置”,两个隐藏字段被创建,并使用latong数据作为它们的值(它们在开始时被删除,这样它们就不会每次都重复)。还有两个按钮,它们有一个点击功能,做同样的事情。 不幸的是,每隔三次左右,它就会奏效。 这里有什么问题?


当前回答

这个库为地理定位调用添加了一个desiredAccuracy和maxWait选项,这意味着它将继续尝试获取位置,直到精度在指定的范围内。

其他回答

这是我解决这个问题的hack方法,至少它在所有当前的浏览器中都有效(在Windows上,我没有Mac):

if (navigator.geolocation) {
    var location_timeout = setTimeout("geolocFail()", 10000);

    navigator.geolocation.getCurrentPosition(function(position) {
        clearTimeout(location_timeout);

        var lat = position.coords.latitude;
        var lng = position.coords.longitude;

        geocodeLatLng(lat, lng);
    }, function(error) {
        clearTimeout(location_timeout);
        geolocFail();
    });
} else {
    // Fallback for no geolocation
    geolocFail();
}

如果有人点击“关闭”或选择“不”或在Firefox上选择“永不共享”选项,这也会起作用。

很笨拙,但很有效。

我一直有类似的问题,并一直在研究浏览器对getCurrentPosition的调用频率有限制的可能性。似乎我可以经常得到一个位置,但如果我刷新页面马上就会超时。如果我等一会儿,我通常可以再次得到一个位置。这通常发生在FF上。在Chrome和Safari中,我还没有注意到getCurrentPosition超时。只是一个想法……

虽然我找不到任何文档来支持这一点,但这是我经过多次测试后得出的结论。也许其他人有这方面的信息?

也许这对一些人有帮助,在Android上我也有同样的问题,但我用它解决了 setTimeout 内部 document.ready 所以它为我工作第二,你必须增加超时以防万一,如果用户允许他的位置几秒钟后,所以我保持它为60000毫秒(1分钟)允许我的成功函数调用,如果用户点击允许按钮在1分钟内。

@brennanyoung的回答很好,但如果你想知道在失败的情况下该怎么做,你可以使用IP地理定位API,如https://ipinfo.io(这是我的服务)。这里有一个例子:

function do_something(coords) {
    // Do something with the coords here
    // eg. show the user on a map, or customize
    // the site contents somehow
}

navigator.geolocation.getCurrentPosition(function(position) { 
    do_something(position.coords);
    },
    function(failure) {
        $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
        do_something(coords);
        });  
    };
});

详情见https://ipinfo.io/developers/replacing-getcurrentposition。

在我们的例子中,它总是第一次工作,但重新运行函数3-4次以上,它就失败了。

简单的解决方法:将其值存储在LocalStorage中。

之前:

navigator.geolocation.getCurrentPosition((position) => {
  let val = results[0].address_components[2].long_name;
  doSthWithVal(val);      
}, (error) => { });

后:

if(localStorage.getItem('getCurrentPosition') !== null) {
  doSthWithVal(localStorage.getItem('getCurrentPosition'));
}
else {
  navigator.geolocation.getCurrentPosition((position) => {
      let val = results[0].address_components[2].long_name;
      localStorage.setItem('getCurrentPosition',val);
      doSthWithVal(val);      
  }, (error) => { });
}