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