如何解决从服务返回的地理位置值未定义
我已将地理定位调用放置在我想在应用程序的不同领域使用的服务中。但是,正在返回 undefined。如何正确返回值以便检索?
服务代码
getUserPosition() {
this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
this.currentLat = position.coords.latitude;
this.currentLng = position.coords.longitude;
return this.latLng;
},(err) => {
console.log('There was an error');
});
}
async ngOnInit() {
// Since ngOnInit() is executed before `deviceready` event,// you have to wait the event.
await this.platform.ready();
await this.loadMap();
this.val = await this.location.getUserPosition();
console.log("I should be here val "+ this.val);
}
解决方法
您似乎没有在 getUserPosition
函数内返回任何内容。您会看到,return this.latLng;
是 promise 中 then
的结果,而不是 getUserPosition
的结果。要解决此问题,您可以例如等待 promise 完成,然后返回值:
async getUserPosition() {
try {
const position = await this.geolocation.getCurrentPosition();
this.latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
this.currentLat = position.coords.latitude;
this.currentLng = position.coords.longitude;
return this.latLng;
},(err) => {
console.log('There was an error');
});
}
我强烈建议使用 typescript 来避免此类错误 - 如果您正确地向函数添加类型,编译器会告诉您该函数应该返回特定类型,但会尝试返回 void
。
从函数返回详细信息
async getUserPosition() {
await this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
this.currentLat = position.coords.latitude;
this.currentLng = position.coords.longitude;
this.locationData = [this.latLng,this.currentLat,this.currentLng];
},(err) => {
console.log('There was an error' + err.message);
});
// return all the details returned from the location
return this.locationData;
}
使用返回的详细信息
this.geolocationData = await this.location.getUserPosition();
this.latLng = this.geolocationData[0];
this.currentLat = this.geolocationData[1];
this.currentLng = this.geolocationData[2];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。