Cordova各個外掛程式使用介紹系列(五)—$cordovaGeolocation擷取當前位置

來源:互聯網
上載者:User

標籤:控制器   項目   false   $cordovageolocation   position   

詳情請看: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()這個函數,然後就可以一直監測到位置資料的變化了


本文出自 “11141997” 部落格,請務必保留此出處http://11151997.blog.51cto.com/11141997/1752538

Cordova各個外掛程式使用介紹系列(五)—$cordovaGeolocation擷取當前位置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.