使用谷歌地图地理编码器返回的回调数据时出现问题



我正在进行这个vue项目,我试图运行这个函数,我使用谷歌地图对地址进行反向地理编码,从该地址提取信息,并使用修改后的回调数据运行不同的函数。我知道地理编码器函数返回了一个promise,并且在promise被填满之前不能使用结果,但我很难让程序的其余部分等待promise被返回。

我的初始设置与本问题中的设置类似使用Google Geocode的回调函数。。。

methods:{
...mapActions({
newFunction: "someModule/newFunction",
}),
getLocationData(callback) {
let geocoder = new this.google.maps.Geocoder();
const latlng = this.mapCenter;   //latitude and longitude positions from elsewhere
if( geocoder ) {
geocoder.geocode({ 'location': latlng }, function (results, status) {
if( status == this.google.maps.GeocoderStatus.OK ) {
callback(results[0].formatted_address);
}
});
}
},
searchLoacal(){
this.getLocationData(function(locationData) {
alert(locationData)
})
}
}

到目前为止,它还可以正常工作,但我不确定如何从getLocationData内部进一步提取回调locationData,并在其他函数中使用它。我试过之类的东西

async searchLocal(){
let result =  await this.getLocationData(function(locationData) {
return locationData
})
this.newFunction(result)
}

其中newFunction以null的输入值运行,而无需等待promise被完全填充或。。。

searchLocal(){
this.getLocationData(function(locationData) {
this.newFunction(locationData)
})
}

其中它读取"typeerror:无法读取属性newFunction of undefined">

我想知道如何在实际等待结果的同时,让外部函数可以访问来自反向地理编码函数的回调。

我通过设置"this"的属性来解决我的问题。"this"是一个单独的变量(self(,它使所有这些方法都可以在回调函数中访问

searchLocal(){
let self = this
this.getLocationData(function(locationData) {
self.newFunction(locationData)
})
}

最新更新