簡體   English   中英

地理位置API不起作用

[英]Geolocation API not working

我正在構建一個天氣頁面,我需要獲取用戶位置才能獲取天氣數據。

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。 即。 它始終設置默認地址,而不是用戶實際地址。 我知道這聽起來很荒謬,但是有什么方法可以避免代碼的“非阻塞”模式。 還是有其他方法可以獲取用戶位置。 我也嘗試了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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM