获取地图边界时返回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的原理。