2017-09-28 50 views
-1

我正在建立一個基於谷歌地圖API Vue(版本2.x)的組件。使功能等待結果在javascript

在這個API中有一個嵌入函數來獲取地圖的邊界:getBounds()(ref)。

在我的代碼,我初始化與邊框對象可在地圖等於0:

  currentBorders: { 
       b: { 
        b: 0, 
        f: 0, 
       }, 
       f: { 
        b: 0, 
        f: 0, 
       }, 
      }, 

在那之後,我顯示具有一定中心的地圖,我執行的getBounds()函數來獲得當前地圖上的價值已經集中後:

 getBorders() { 
      console.log(this.currentBorders); // -> prints the object with all values equal to 0 

      this.currentBorders = this.$map.getBounds(); 

      console.log(this.currentBorders); // -> prints undefined 

      return { 
       llc_lat: this.currentBorders.f.b, 
       llc_lng: this.currentBorders.b.b, 
       urc_lat: this.currentBorders.f.f, 
       urc_lng: this.currentBorders.b.f, 
      }; 
     }, 

現在的問題是,第一個執行過程中我必須設置爲0 currentBorders,但的getBounds第一次執行()返回不確定,可能是因爲地圖尚未加載。

我想要做的就是阻止代碼的執行,直到getBounds返回一些有意義的東西。這是要走的路嗎?我怎樣才能做到這一點?

編輯: 這是我如何初始化地圖,通過deferredReady:

deferredReady() { 
     this.$map.setOptions({ 
      styles: mapStyles(), 
     }); 

     this.initializeMapOverlay(); 
     this.canvasContext = this.mapCanvas.getContext("2d"); 
     this.$map.addListener("idle", this.idleHandler); 
     this.$map.addListener("zoom_changed",() => { 
      this.resizeCanvas(); 
      this.clearCanvas(); 
     }); 
     this.$map.addListener("mousemove", this.mouseoverHandler); 
     this.$map.addListener("drag", this.fetchHexagons()); 
    }, 
+1

你能告訴我們關於你的地圖實例和你getBounrds()調用的代碼嗎? –

+0

爲什麼不等待地圖初始化之後再調用'getBounds'?或者是你的問題? – thanksd

回答

0

你可能要等到你知道地圖是完全加載到執行代碼。我們可以這樣做是這樣的:

google.maps.event.addListenerOnce(map, 'idle', function(){ 
    // idle state is triggered once map is fully loaded, or failed to load. 
}); 

這樣就可以保證你的代碼將只運行圖時是滿載以及所有相應的對象是可訪問。把你的代碼放在事件監聽器的主體中。

看看這是否適合你。

編輯

我看到你有你的代碼中定義的空閒事件。我不確定vue是如何工作的,但也許有一種方法可以在該事件運行後運行您的代碼。也許把代碼放在你的idleHandler函數中,看看它是否在那裏工作。