javascript - 地理定位 API 不起作用

标签 javascript jquery geolocation weather

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

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 数据库 Api,但它运行不精确。

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

最佳答案

您必须使用 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>

关于javascript - 地理定位 API 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38662208/

相关文章:

javascript - 从字符串中删除日期

javascript - 选择两个特定行之间的所有 HTML 表格行

google-maps - 从坐标确定市区

将笛卡尔系统转换为纬度、经度和高度的 c++ 库

javascript - 如何获取Firebase中的唯一ID

javascript d3 刻度格式

javascript - jQuery自定义过滤器问题: element stack is way too much

json - 查询 Geonames API 以仅获取城市国家名称

javascript - 无法解析不同文化的日期

javascript - jQuery : pass argument to ajax error function