2017-03-16 51 views
0

工作,我有這樣的代碼:地理位置並不簡單的JS

document.querySelector("#posBtn").addEventListener("click", function() { navigator.geolocation.getCurrentPosition(PositionFunction); }); 

function PositionFunction(p) { 

    console.log(p.coords.longitude); 
} 

這看起來很簡單,但它不工作。爲什麼?

+0

添加一個錯誤回調函數來調試它。請參閱https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition – sking

回答

0

它似乎工作得很好!你會得到一個警告,即HTTP不再支持GeoLocation,你需要使用HTTPS才能工作。

getCurrentPosition()和watchPosition()不再適用於不安全的起源。要使用此功能,您應該考慮將應用程序切換到安全的來源,例如HTTPS。

document.querySelector("#posBtn").addEventListener("click", function() { navigator.geolocation.getCurrentPosition(PositionFunction); }); 
 

 
function PositionFunction(p) { 
 

 
    console.log(p.coords.longitude); 
 
}
<button id="posBtn"> 
 
Get Longitude 
 
</button>

更多細節here

這裏的工作example of your code

0

嘗試捕捉錯誤,要知道爲什麼它不工作

document.querySelector("#posBtn").addEventListener("click",function(){ 
     if (navigator.geolocation) { 
       navigator.geolocation.getCurrentPosition(PositionFunction, showError); 
      } else { 
       console.log("Geolocation is not supported by this browser."); 
      } 

     }); 

     function PositionFunction(p) { 
     console.log(p.coords.longitude); 
     }; 

     function showError(error) { 
     switch(error.code) { 
      case error.PERMISSION_DENIED: 
       console.log("User denied the request for Geolocation."); 
       break; 
      case error.POSITION_UNAVAILABLE: 
       console.log("Location information is unavailable."); 
       break; 
      case error.TIMEOUT: 
       console.log("The request to get user location timed out."); 
       break; 
      case error.UNKNOWN_ERROR: 
       console.log("An unknown error occurred."); 
       break; 
     } 
    } 

查看實例:https://jsfiddle.net/ozmsq23w/6/

+0

沒有錯誤 –