【问题标题】:Make function wait for result in javascript使函数在javascript中等待结果
【发布时间】:2017-09-28 13:27:40
【问题描述】:

我正在使用基于谷歌地图 API 的 Vue(2.x 版)构建一个组件。

在这个 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,
          };
      },

现在的问题是,在第一次执行期间,我将 currentBorders 设置为 0,但 getBounds() 的第一次执行返回 undefined,可能是因为尚未加载地图。

我想做的是阻止该代码的执行,直到 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());
  },

【问题讨论】:

  • 你能告诉我们关于你的地图实例化和你getBounrds()调用的代码吗?
  • 为什么不等到地图初始化后再调用getBounds?还是这是你的问题?

标签: javascript google-maps vue.js


【解决方案1】:

您可能应该等到知道地图已完全加载后再执行您的代码。我们可以这样做:

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

这样您可以保证您的代码仅在地图完全加载且所有相应对象都可访问时运行。只需将您的代码放在事件侦听器的主体中即可。

看看这是否对你有用。

编辑

我看到您的代码中确实定义了空闲事件。我不确定 vue 是如何工作的,但也许有一种方法可以在运行该事件后运行您的代码。或许将代码放在您的 idleHandler 函数中,看看它是否在那里工作。

【讨论】:

    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 2019-06-30
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多