Cordova各個插件使用介紹系列(五)—$cordovaGeolocation獲取當前位置

詳情請看:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/cordova-5-cordovageolocation/javascript

$cordovaGeolocation是能夠獲取當前位置的ngCordova插件,在項目中應用到,在這裏講解一下:java

一、首先須要下載此插件,命令是:git

cordova plugin add cordova-plugin-geolocation

  

二、在JS中的代碼以下,這個代碼寫在相應的控制器裏而且依賴‘$cordovaGeolocation’,記得在app.js裏依賴‘ngCordova’,這是ngCordova官網的控制器裏面的代碼,:app

module.controller('GeoCtrl', function($cordovaGeolocation) {

  var posOptions = {timeout: 10000, enableHighAccuracy: false};
  $cordovaGeolocation
    .getCurrentPosition(posOptions)
    .then(function (position) {
      var lat  = position.coords.latitude
      var long = position.coords.longitude
    }, function(err) {
      // error
    });
});

  

三、在項目中,我須要實時監測到地理位置,所以用到了AngularJs裏面的$broadcast,$on;$broadcast能夠監測到值的變化,而$on就是一旦監測的值發生變化,能夠觸發到它,結合上面所講到的獲取位置的插件,這樣就能夠一直監測位置的變化了,代碼以下:函數

module.controller('GeoCtrl', function($cordovaGeolocation) {

  function getCurrentPosition()
	{
	var posOptions = {timeout: 10000, enableHighAccuracy: false};
  	$cordovaGeolocation
    .getCurrentPosition(posOptions)
    .then(function (position) {
     $rootScope.$broadcast('selfLocation:update', position);
      var lat  = position.coords.latitude
      var long = position.coords.longitude
    }, function(err) {
      // error
    });
});

  

在其餘須要得到position的控制器裏,要添加$on:插件

$scope.$on('selfLocation:update', function (_, location) {
  //不斷更新的值
  $scope.currentPosition = {
    latitude: location.latitude,
    longitude: location.longitude
  };
});

這樣子只要調用getCurrentPosition()這個函數,而後就能夠一直監測到位置數據的變化了cordova

相關文章
相關標籤/搜索