封装Google Maps API时,如何在show()方法外部访问Map实例?
解决Google Maps API类中Map实例跨方法访问的问题
你遇到的setMap: not an instance of Map错误,核心原因是**map只是show()方法内的局部变量**,类的其他方法(比如marker())根本无法访问到这个Map实例。
最直接的解决方案就是把Map实例设为类的属性,这样整个类的所有方法都能共享这个实例。具体修改步骤如下:
- 在构造函数中初始化一个类属性来存储Map实例
- 在
show()方法中创建Map实例时,赋值给这个类属性而非局部变量 - 在
marker()方法中引用类属性的Map实例
修改后的完整代码如下:
export default class InitMap { constructor(element) { this.element = element; // 初始化类属性存储Map实例 this.map = null; } show() { // 将Map实例赋值给类属性this.map this.map = new google.maps.Map(document.getElementById(this.element), this.options()); this.addMarker(); console.log(this.addMarker()); // 现在会返回Marker实例 } options() { return { zoom: 4, center: { lat: -25.363, lng: 131.044 }, disableDefaultUI: true, zoomControl: true, scaleControl: false, streetViewControl: false, rotateControl: false, fullscreenControl: true } } marker(location) { // 引用类属性的Map实例 return new google.maps.Marker({ position: location, map: this.map, title: 'test' }); } addMarker() { let uluru = new google.maps.LatLng(-25.363, 131.044); // 返回创建的Marker实例,避免console.log输出undefined return this.marker(uluru); } }
这样修改后,marker()方法就能正确访问到Map实例,标记也能正常添加到地图上了。另外我还调整了addMarker()方法,让它返回创建的Marker实例,这样console.log就不会输出undefined了。
内容的提问来源于stack exchange,提问作者Greg Ostry
相关产品推荐
相关产品推荐

