Ionic - Cordova 地理位置



此外掛用於向 Ionic 應用新增地理位置外掛。

使用地理位置

使用地理位置外掛的方法很簡單。我們需要從命令提示符視窗安裝此外掛。

C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-geolocation

下面的控制器程式碼使用了兩種方法。第一個是 `getCurrentPosition` 方法,它將顯示使用者的裝置當前的緯度和經度。第二個是 `watchCurrentPosition` 方法,當位置改變時,它將返回裝置的當前位置。

控制器程式碼

.controller('MyCtrl', function($scope, $cordovaGeolocation) {
   var posOptions = {timeout: 10000, enableHighAccuracy: false};
   $cordovaGeolocation
   .getCurrentPosition(posOptions)
	
   .then(function (position) {
      var lat  = position.coords.latitude
      var long = position.coords.longitude
      console.log(lat + '   ' + long)
   }, function(err) {
      console.log(err)
   });

   var watchOptions = {timeout : 3000, enableHighAccuracy: false};
   var watch = $cordovaGeolocation.watchPosition(watchOptions);
	
   watch.then(
      null,
		
      function(err) {
         console.log(err)
      },
	   function(position) {
         var lat  = position.coords.latitude
         var long = position.coords.longitude
         console.log(lat + '' + long)
      }
   );

   watch.clearWatch();
})

您可能也注意到了 `posOptions` 和 `watchOptions` 物件。我們使用 `timeout` 來調整允許經過的最大時間(以毫秒為單位),並將 `enableHighAccuracy` 設定為 false。可以將其設定為 `true` 以獲得最佳結果,但有時可能會導致一些錯誤。還有一個 `maximumAge` 選項,可以用來顯示接受舊位置的程度。它使用毫秒,與 timeout 選項相同。

當我們啟動應用程式並開啟控制檯時,它將記錄裝置的緯度和經度。當我們的位置改變時,`lat` 和 `long` 值將發生變化。

廣告