我有一个很简单的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数据作为它们的值(它们在开始时被删除,这样它们就不会每次都重复)。还有两个按钮,它们有一个点击功能,做同样的事情。 不幸的是,每隔三次左右,它就会奏效。 这里有什么问题?


当前回答

@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。

其他回答

这已经是一个老问题了,但所有的答案都不能解决我的问题,所以让我们加上我最终找到的那个。它闻起来像一种hack(它确实是一种),但在我的情况下总是有效。对你的处境也抱有希望。

//Dummy one, which will result in a working next statement.
navigator.geolocation.getCurrentPosition(function () {}, function () {}, {});
//The working next statement.
navigator.geolocation.getCurrentPosition(function (position) {
    //Your code here
}, function (e) {
    //Your error handling here
}, {
    enableHighAccuracy: true
});

当getCurrentPosition失败时,使用IP地址地理位置服务作为回退方法可能是个好主意。例如,我们的api https://ip-api.io

$.getJSON("http://ip-api.io/json/",
    function(result) {
        console.log(result);
    });

你不会得到一个错误消息,因为默认情况下它没有超时(至少我认为)。我用firefox也遇到过同样的问题,只是对我来说,firefox总是超时。您可以像这样自己设置一个超时。

我的功能在chrome中工作得很好,但我每次在firefox中都会超时。

    navigator.geolocation.getCurrentPosition(
        function(position) {
            //do succes handling
        },
        function errorCallback(error) {
            //do error handling
        },
        {
            timeout:5000
        }
    );

我建议你仔细观察你的错误。一切都被期待。为每件事都准备一个备份计划。我使用一些默认值或值从我的数据库自己的情况下谷歌地理位置和导航地理位置失败。

我有一个部分的答案,但可惜不是一个完整的答案。

首先,要意识到getCurrentPosition的默认超时是无限的(!)。这意味着如果getCurrentPosition挂在后端某个位置,则永远不会调用错误处理程序。

为了确保你得到一个超时,添加可选的第三个参数到你对getCurrentPosition的调用,例如,如果你想让用户等待不超过10秒,然后给他们一个线索发生了什么,使用:

navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000});

其次,我在不同的环境中经历了非常不同的可靠性。在家里,我在一两秒钟内就会收到回复,尽管准确率很低。

然而,在工作中,我经历了相当奇怪的行为变化:地理定位在一些电脑上一直有效(当然IE除外),另一些只能在chrome和safari上工作,但不能在firefox上工作(壁虎问题?),另一些只工作了一次,然后就失败了——这种模式每小时都在变化,每天都在变化。有时你有一台“幸运”的电脑,有时没有。也许满月时宰山羊会有帮助?

我还不能理解这一点,但我怀疑后端基础设施比各种推动这一功能的书籍和网站上宣传的更不平衡。如果您希望错误处理程序正常工作,我真的希望他们能更直接地说明这个特性是多么不可靠,以及超时设置是多么重要。

今天我一直在试着教学生这些东西,遇到了一个尴尬的情况,我自己的电脑(在投影仪和几个大屏幕上)无声地失败了,而大约80%的学生几乎立即得到了结果(使用完全相同的无线网络)。当我的学生也犯拼写错误和其他错误时,当我自己的电脑也出现故障时,解决这些问题是非常困难的。

感谢每个人的投入,这对我很有帮助。

除了必须使用watchPosition()而不是getCurrentPosition()之外,我还发现需要将调用从document.ready()内移动到头部。