我正在尝试使用 kml 图层初始化谷歌地图。我已经验证了 KML 层是否正常工作,如果我使用原版 JS,我可以让它工作(请参阅工作小提琴:https://jsfiddle.net/x00t510d/2/(,但是我使用的是角度并在 ngOnInit(( 中初始化地图。
下面的代码生成"InvalidValueError: setMap: not a instance of Map"的结果。
export class MapComponent implements OnInit {
@ViewChild('gmap') gmapElement: any;
map: google.maps.Map;
constructor() { }
ngOnInit() {
let mapProp: any = {
center: new google.maps.LatLng(44.475, -73.212),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
let ctaLayer = new google.maps.KmlLayer({
url: 'https://sites.google.com/site/freeparkingburlington/home/freeParking.kml',
map: mapProp
});
return this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}
}
地图已初始化,但图层未初始化。有没有人深入了解如何在这种情况下更有效地使用 KML 图层?
问题在于初始化地图,以及 ngOnInit 生命周期挂钩上的 kml 图层。 地图应该在ngOnInit((中初始化,一旦加载,调用ngAfterContentInit将图层添加到地图中。
请参阅此处的代码:
export class MapComponent implements OnInit, AfterContentInit {
@ViewChild('gmap') gmapElement: any;
map: google.maps.Map;
//ctaLayer: google.maps.KmlLayer;
constructor() { }
ngOnInit() {
let mapProp: any = {
center: new google.maps.LatLng(44.475, -73.212),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}
ngAfterContentInit(){
let ctaLayer = new google.maps.KmlLayer({
url: 'https://sites.google.com/site/freeparkingburlington/home/freeParking.kml',
map: this.map
});
}
}