Cordova各个插件使用介绍系列(五)—$cordovaGeolocation获取当前位置
详情请看:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/cordova-5-cordovageolocation/
$cordovaGeolocation是可以获取当前位置的ngCordova插件,在项目中应用到,在这里讲解一下:
1、首先需要下载此插件,命令是:
cordovapluginaddcordova-plugin-geolocation
2、在JS中的代码如下,这个代码写在相应的控制器里并且依赖‘$cordovaGeolocation’,记得在app.js里依赖‘ngCordova’,这是ngCordova官网的控制器里面的代码,:
module.controller('GeoCtrl',function($cordovaGeolocation){varposOptions={timeout:10000,enableHighAccuracy:false};$cordovaGeolocation.getCurrentPosition(posOptions).then(function(position){varlat=position.coords.latitudevarlong=position.coords.longitude},function(err){//error});});
3、在项目中,我需要实时监测到地理位置,因此用到了AngularJs里面的$broadcast,$on;$broadcast可以监测到值的变化,而$on就是一旦监测的值发生变化,可以触发到它,结合上面所讲到的获取位置的插件,这样就可以一直监测位置的变化了,代码如下:
module.controller('GeoCtrl',function($cordovaGeolocation){functiongetCurrentPosition(){varposOptions={timeout:10000,enableHighAccuracy:false};$cordovaGeolocation.getCurrentPosition(posOptions).then(function(position){$rootScope.$broadcast('selfLocation:update',position);varlat=position.coords.latitudevarlong=position.coords.longitude},function(err){//error});});
在其他需要获得position的控制器里,要添加$on:
$scope.$on('selfLocation:update',function(_,location){//不断更新的值$scope.currentPosition={latitude:location.latitude,longitude:location.longitude};});
这样子只要调用getCurrentPosition()这个函数,然后就可以一直监测到位置数据的变化了
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。