標籤:控制器 項目 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擷取當前位置