2014-10-01 55 views
0

我試圖做一個簡單的地理定位HTML5:地理位置許可

$(function() { 
    var currentLatitude =""; 
    var currentLongitude =""; 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition, showError); 
    function showPosition(position) { 
      currentLatitude = position.coords.latitude; 
      currentLongitude = position.coords.longitude;             
     } 
    } else { 
     // location based on the IP - less accurate 

    } 

,誤差在許可地點錯誤,即使我有我的網站上異常(本地運行)。 我的第二個選擇是通過IP(ipinfo.io):

function showError(error) { 
     var x = $('#curr_loc_target'); 

     switch(error.code) { 
     case error.PERMISSION_DENIED: 
      x.html("User denied the request for Geolocation."); 
      jQuery.get("http://ipinfo.io/json", function (response) 
       { 
        console.log(response) ; 
        currentLatitude = response.loc.split(',')[0]; 
        currentLongitude = response.loc.split(',')[1]; 
        console.log("lat" + currentLatitude+ "," + "lngs" +currentLongitude) ; 
       }); 
      break; 
     case error.POSITION_UNAVAILABLE: 
      x.html("Location information is unavailable."); 
      break; 
     case error.TIMEOUT: 
      x.html("The request to get user location timed out."); 
      break; 
     case error.UNKNOWN_ERROR: 
      x.html("An unknown error occurred."); 
      break; 
     } 
    } 

和它的作品,但它是不準確的。 我需要做的就是發送lat,lng到我的服務器,如果它不是本地的,它會工作嗎? 或任何人都知道解決這個錯誤的方法?

+0

我真的不知道ipinfo有什麼樣的準確性,但很顯然,基於IP的地理位置有幾個缺點:它不會在本地IP上工作,如果用戶在代理後面,它會返回錯誤的位置並不總是很準確。 我編輯了一個服務:userinfo.io,它爲您提供來自IP的地理位置(和其他信息)。到目前爲止,我的測試表明它非常準確,但它具有與我提到的相同的缺點。我依靠幾個地理位置提供商,所以也許會更精確一些,但我無法確定。 – 2014-10-02 16:39:13

回答

0

在我的網站上工作的代碼。您似乎已停用了瀏覽器上的地理位置跟蹤功能,直接向您發送錯誤情況。請注意,它將要求用戶明確授予您獲取位置跟蹤信息的權限。

0

我試圖測試地理位置,從我的本地機器上打開.html文件,太 - 和Chrome一直在這裏給我的錯誤回調:啓用

navigator.geolocation.getCurrentPosition(success, error); 

地理位置跟蹤inspite。其他瀏覽器給回調成功。 然後我把頁面放到了主機上,並且它在所有瀏覽器(包括谷歌瀏覽器)中都成功了。 當你的網站在本地運行時,你可能有類似的原因與位置的許可。