谷歌地图无法有效获取地图边界的原因

获取地图边界时返回undefined

            initGoogleMap() {
                const hook = this.hook = document.querySelector(".map");
                this.map   = new google.maps.Map(hook, {
                    center: this.coordinates[0], zoom: 4,
                });
                this.initMarkers(this.coordinates);
                const bounds = this.map.getBounds();
            }

官方文档中指出当创建谷歌地图时如果没有指定center或者zoom的值就会发生这种情况。
If the map is not yet initialized (i.e. the mapType is still null), or center and zoom have not been set then the result is null or undefined.
但是此处已经设置了center和zoom的值,结果依然拿不到。那只能存在一种可能性:在执行this.map.getBounds()时,地图还没有初始化完毕。很有可能是地图的初始化是一个远程方法调用。存在网络时延。

解决方案:

            initGoogleMap() {
                const hook = this.hook = document.querySelector(".map");
                this.map   = new google.maps.Map(hook, {
                    center: this.coordinates[0], zoom: 4,
                });
                this.initMarkers(this.coordinates);

                setTimeout(() => {
                    const bounds = this.map.getBounds();
                    window.alert(bounds);
                }, 0);
            }

需要了解setTimeout的原理。

阅读 3.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进