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

相关文章
相关标签/搜索