【问题标题】:Geolocation API not working地理位置 API 不工作
【发布时间】:2016-07-29 15:15:53
【问题描述】:

我正在构建一个天气页面,我需要获取用户位置以获取天气数据。

if ((navigator.geolocation)&&(location!=null)) {
    var locations = null;
    window.navigator.geolocation.getCurrentPosition(function(position){
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
        locations = latitude+'/'+longitude;
        show_all_weather_components();  
        console.log("1");
    }); 
}
/* If location is not found the set default location as USDC0001, which is default code for washington DC. */

var locations= !locations?"USDC0001":locations;
console.log("2");

我在控制台中首先获得 2。 IE。它总是设置默认地址而不是用户实际地址。我知道这听起来很荒谬,但有什么方法可以避免这里代码的“非阻塞”模式。 还是有其他方法可以获取用户位置。我也尝试了 ip database Api,但它没有精确地工作。

有一次我想在 if 条件部分下面放一个延迟,但是由于这个天气应用程序的不同模块,我的页面已经很慢了。任何想法将不胜感激。 谢谢

【问题讨论】:

  • locations 变量始终为空,因此如果条件失败
  • navigator.geolocation 不是 Jquery 的一部分,而是 HTML 5 的一部分。它还提示用户在页面加载时共享位置。在用户分享之前,您将无法获取用户的用户位置。
  • 我明白了,即使我之前允许共享位置,这也需要时间,并且 console.log("2") 比 console.log("1) 更早执行。
  • 好的,我将尝试取出 var location =null,然后检查
  • 还是不行。结果相同

标签: javascript jquery geolocation weather


【解决方案1】:

您必须使用 getCurrentPosition 的其他参数。这是一个例子:

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
</head>
<body>
  <div id="result"></div>
  <script>
     var result = document.getElementById('result');
     if (navigator.geolocation && location != null) {        
       window.navigator.geolocation.getCurrentPosition(function(position){
         result.text = position.coords.latitude + '/' + position.coords.longitude;
       }, function(error) {           
         switch(error.code) {
           case error.PERMISSION_DENIED:
             result.innerHTML = "Denied request for Geolocation."
             break;
           case error.POSITION_UNAVAILABLE:
             result.innerHTML = "Location unavailable."
             break;
          case error.TIMEOUT:
             result.innerHTML = "Location request timed out." 
             break;
          case error.UNKNOWN_ERROR:
             result.innerHTML = "An unknown error occurred."
             break;
         }
       }, { timeout: 1000, maximumAge: 1000 }); 
     }
  </script>
</body>

【讨论】:

  • 谢谢,缺少的就是第三个参数。
猜你喜欢
  • 2011-05-11
  • 2020-06-04
  • 2011-08-28
  • 2012-02-24
  • 1970-01-01
  • 2011-02-08
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多