【问题标题】:what make getCurrentPosition fail?是什么让 getCurrentPosition 失败?
【发布时间】:2012-08-28 02:54:02
【问题描述】:

我做了一个简单的网站,上面有 javascript,它调用:

navigator.geolocation.getCurrentPosition(show_map, show_map_error);

我已将网站放到互联网上。我试图从不同位置的不同 PC(没有 GPS 小工具)打开网站。一个来自我家,一个来自朋友办公室。

但脚本并不总能获得位置。 会有什么问题?

谢谢。

【问题讨论】:

    标签: w3c-geolocation


    【解决方案1】:

    该方法不能保证返回位置,尤其是在没有连接 GPS 的情况下。

    您可以尝试获取缓存位置。请参阅 API 规范中的以下内容

    // Request a position. We only accept cached positions, no matter what 
    // their age is. If the user agent does not have a cached position at
    // all, it will immediately invoke the error callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:Infinity, timeout:0});
    
    function successCallback(position) {
      // By setting the 'maximumAge' to Infinity, the position
      // object is guaranteed to be a cached one.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no cached position available at all, the user agent 
      // will immediately invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
      if (position.timestamp < freshness_threshold && 
          position.coords.accuracy < accuracy_threshold) {
        // The position is relatively fresh and accurate.
      } else {
        // The position is quite old and/or inaccurate.
      }
    }
    
    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no cached position exists at all.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }
    
    function doFallback() {
      // No cached position available at all.
      // Fallback to a default position.
    }
    

    【讨论】:

    • 如果PC没有连接GPS,为什么我可以得到位置?
    • 我有一部集成 GPS 的黑莓手机。手机的地图应用程序可以从其 GPS 获取位置。但是该网站无法获得位置。有什么问题?
    • 根据规范,设备可以使用多种方法来近似位置,包括IP地址。
    • 我不确定黑莓的情况,但可能浏览器没有设置为使用 GPS 位置,或者您没有授予它这样做的权限。
    • 我在一个网站上发现黑莓有不同的方式来访问它的 GPS 坐标。稍后我会发布网址。
    猜你喜欢
    • 2015-06-25
    • 2014-07-31
    • 2020-10-27
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2016-11-07
    相关资源
    最近更新 更多