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


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

$cordovaGeolocation是可以獲取當前位置的ngCordova插件,在項目中應用到,在這里講解一下:

1、首先需要下載此插件,命令是:

cordova plugin add cordova-plugin-geolocation

  

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

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
    });
});

  

3、在項目中,我需要實時監測到地理位置,因此用到了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()這個函數,然后就可以一直監測到位置數據的變化了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM