我正在使用离子3基于位置的工作。我无法在这里获得纬度和经度的当前位置。我提到了我可用的代码。它在浏览器级别上运行良好,但在移动设备中无法正常工作。
码
$ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
$ npm install --save @ionic-native/geolocation
import { Geolocation } from '@ionic-native/geolocation';
constructor(private geolocation: Geolocation) {}
this.geolocation.getCurrentPosition().then((resp) => {
console.log( resp.coords.latitude)
console.log( resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
});
答案 0 :(得分:4)
试试这个:
import { Geolocation } from '@ionic-native/geolocation';
import { Platform } from 'ionic-angular';
//Set the properties in this class
long: any; //longitude
lati: any; //latitude
constructor(private platform: Platform, private geolocation: Geolocation) {
this.platform.ready().then(()=>{
//set options..
var options = {
timeout: 20000 //sorry I use this much milliseconds
}
//use the geolocation
this.geolocation.getCurrentPosition(options).then(data=>{
this.long = data.coords.longitude;
this.lati = data.coords.latitude;
}).catch((err)=>{
console.log("Error", err);
});
});
}
让它在构造函数中。不要忘记同意位置隐私权限,同时在您的Android设备上启用位置选项(尽管这很可能)。
答案 1 :(得分:2)
尝试在ionViewDidLoad()或ngAfterViewInit()方法中调用地理定位函数。
import { Geolocation } from '@ionic-native/geolocation';
constructor(private geolocation: Geolocation) {}
ngAfterViewInit(){
this.geolocation.getCurrentPosition().then((resp) => {
console.log( resp.coords.latitude)
console.log( resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
});
}
我希望这能解决你的问题!
答案 2 :(得分:1)
import { Geolocation } from '@ionic-native/geolocation';
import { Platform } from 'ionic-angular';
//Set the properties in this class
long: any; //longitude
lati: any; //latitude
constructor(private platform: Platform, private geolocation: Geolocation) {
this.platform.ready().then(()=>{
//set options..
var options = {
enableHighAccuracy: true, timeout: 60000, maximumAge: 0
};
//use the geolocation
this.geolocation.getCurrentPosition(options).then(data=>{
this.long = data.coords.longitude;
this.lati = data.coords.latitude;
}).catch((err)=>{
console.log("Error", err);
});
let watch = this.geolocation.watchPosition(options);
watch.subscribe((data) => {
let lat_lng = data.coords.latitude+","+data.coords.longitude;
});
});
}