简体   繁体   English

地理位置API不起作用

[英]Geolocation API not working

I am building a weather page and I need to grab the user location in order to get the weather data. 我正在构建一个天气页面,我需要获取用户位置才能获取天气数据。

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");

I am getting 2 first in my console. 我的控制台先获得2。 ie. 即。 It is always setting default address rather than the user actual address. 它始终设置默认地址,而不是用户实际地址。 I know it sounds ridiculous but is there some way to avoid the "non-blocking" mode of the code here. 我知道这听起来很荒谬,但是有什么方法可以避免代码的“非阻塞”模式。 Or is there some other way to grab the user location. 还是有其他方法可以获取用户位置。 I tried the ip database Api as well, but it didn't worked with precision. 我也尝试了ip数据库Api,但是它不能精确工作。

At one point I thought of to put a delay just below the if condition part, but Due to different modules of this weather app, my page is already very slow. 有一次我想到了将延迟放在if条件部分的下面,但是由于这个天气应用程序的模块不同,我的页面已经很慢了。 Any Idea will be appreciated. 任何想法将不胜感激。 Thank you 谢谢

You have to use the other arguments of getCurrentPosition. 您必须使用getCurrentPosition的其他参数。 Here is an example: 这是一个例子:

<!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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM