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


当前回答

我终于找到了一个工作版本的firefox, chrome和默认导航器在android(仅4.2测试):

function getGeoLocation() {
        var options = null;
        if (navigator.geolocation) {
            if (browserChrome) //set this var looking for Chrome un user-agent header
                options={enableHighAccuracy: false, maximumAge: 15000, timeout: 30000};
            else
                options={maximumAge:Infinity, timeout:0};
            navigator.geolocation.getCurrentPosition(getGeoLocationCallback,
                    getGeoLocationErrorCallback,
                   options);
        }
    }

其他回答

对于开发iPhone应用程序的人来说……

如果你的代码在ios9 +的UIWebView中运行,那么你必须在应用的plist中设置NSLocationWhenInUseUsageDescription。

如果你不设置它,那么getCurrentPosition将永远不会回调,用户也永远不会被提示。

这对我来说每次都管用:

navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});

虽然它不是很准确。有趣的是,在同一台设备上,如果我运行这个程序,它会把我拖走大约100米(每次),但如果我去谷歌的地图,它会准确地找到我的位置。因此,尽管我认为enableHighAccuracy: true有助于它始终如一地工作,但它似乎并没有使它更准确……

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

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

在2017年,我仍然得到了不稳定的结果,我有一个理论:API文档说调用现在只在“安全上下文中”可用,即通过HTTPS。我有麻烦得到一个结果在我的开发环境(http在localhost),我相信这就是为什么。

我在使用Firefox的响应式设计模式时就遇到过这种情况。已经提交了一份错误报告。现在,在使用地理定位API时不要使用响应式设计模式。