geolocation定位是调用手机gps,获取坐标的,在实际中用处较广
(1)安装插件
ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="允许App使用GPS定位功能"
npm install --save @ionic-native/geolocation
(2)app.moudule.ts中引入及声明
import { Geolocation } from '@ionic-native/geolocation';
在providers中声明Geolocation
providers: [
StatusBar,
SplashScreen,
Camera,
ImagePicker,
Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
(3)在使用的页面中引用声明
import { Geolocation } from '@ionic-native/geolocation';
按照官方的还引用了Platform
import { NavController,Platform} from 'ionic-angular';
在构造函数中声明
constructor(public navCtrl: NavController,public menuCtrl: MenuController,private platform: Platform,private geolocation: Geolocation) {
}
(4)使用
//官方
gps(){
this.platform.ready().then(() => {
// get current position
this.geolocation.getCurrentPosition().then(pos => {
alert('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
});
const watch = this.geolocation.watchPosition().subscribe(pos => {
alert('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
});
// to stop watching
watch.unsubscribe();
});
}
gps2(){
this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
alert(resp.coords.latitude+','+resp.coords.longitude);
}).catch((error) => {
console.log('Error getting location', error);
});
}
敲黑板,注意了
ios 必须在info.plist加上权限设置
Privacy - Location When In Use Usage Description——————允许app使用GPS定位
Privacy - Location Always Usage Description—————————始终允许App使用GPS定位功能
网友评论