使用从google maps geocoder返回的回调数据有问题

问题描述 投票:0回答:1

我正在做这个vue项目,我试图运行这个函数,在那里我使用google地图对一个地址进行反向地理编码,从该地址提取信息,并使用修改后的回调数据运行一个不同的函数。我知道geocoder函数会返回一个承诺,而且在承诺得到满足之前,你不能使用结果,但我很难让我的程序的其余部分等到承诺被返回。

我的初始设置就像这个问题中提到的那样。使用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,而不需要等待承诺被满足或...

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

其中它读到 "typerror: unable to read property newFunction of undefined"。

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

javascript google-maps vue.js asynchronous reverse-geocoding
1个回答
0
投票

我解决了我的问题,把 "这个 "的属性是一个单独的变量(self),这使得所有这些方法可以在回调函数内进行访问

searchLocal(){
      let self = this
      this.getLocationData(function(locationData) {
         self.newFunction(locationData)
       })
    }
© www.soinside.com 2019 - 2024. All rights reserved.