2015-07-01 164 views
2

我正在編寫一個Cordova/Phonegap應用程序,我想使用Geolocation插件來獲取經度和緯度。這是我的代碼:科爾多瓦/ Phonegap地理定位

$scope.showCoord = function() { 
     var onSuccess = function(position) { 
      console.log("Latitude: "+position.coords.latitude); 
      console.log("Longitude: "+position.coords.longitude); 
     }; 

     function onError(error) { 
      console.log("Code: "+error.code); 
      console.log("Message: "+error.message); 
     }; 

     navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }); 
    } 

當我嘗試這個插件用它工作得很好,但是當我嘗試沒有GPS我收到超時......我更改超時100000但不工作的GPS。此外在我的config.xml中添加了以下代碼:

<feature name="Geolocation"> 
     <param name="android-package" value="org.apache.cordova.GeoBroker" /> 
    </feature> 

我該如何解決?

回答

7

更新:基於您的評論下面我已經重寫我的答案

當您設置enableHighAccuracy: true,應用程序是說給OS「給我從GPS硬件高精度位置」。如果在OS設置中啓用了GPS,則GPS硬件可用,因此請求高精度位置將導致OS使用GPS硬件來獲取高精度位置。但是,如果在OS設置中禁用了GPS,則應用程序請求的高精度位置不能由操作系統提供,因此會導致錯誤回調。

如果設置enableHighAccuracy: false,應用程序是說給OS「給我任何精度的位置」,那麼操作系統將使用細胞三角/ WIFI返回一個位置(或GPS,如果目前由另一個應用程序激活) 。因此,爲了迎合高精度和低精度的位置,您可以首先嚐試高精度位置,如果失敗,則請求低精度位置。例如:

var maxAge = 3000, timeout = 5000; 

var onSuccess = function(position) { 
    console.log("Latitude: "+position.coords.latitude); 
    console.log("Longitude: "+position.coords.longitude); 
}; 

function onError(error) { 
    console.log("Code: "+error.code); 
    console.log("Message: "+error.message); 
}; 

navigator.geolocation.getCurrentPosition(onSuccess, function(error) { 
    console.log("Failed to retrieve high accuracy position - trying to retrieve low accuracy"); 
    navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: maxAge, timeout: timeout, enableHighAccuracy: false }); 
}, { maximumAge: maxAge, timeout: timeout, enableHighAccuracy: true }); 
+0

對不起,我想獲取GPS時,它是積極的,當它關閉時我想接收來自網絡 – Ragnarr

+1

的座標它不工作對我來說......如果我設置了超時1分鐘,我總是獲得超時...我正在測試我的android設備 – Ragnarr

+0

此外,如果我關閉連接,我必須收到POSITION_UNAVAILABLE時收到超時 – Ragnarr