使用Angular使用kml图层初始化google地图:InvalidValueError:setMap:不是Map的实例

问题描述 投票:0回答:1

我正在尝试使用kml图层初始化Google地图。我已经验证了KML层正在工作,如果我使用vanilla JS,我可以使用它(请参阅工作小提琴:https://jsfiddle.net/x00t510d/2/),但是我正在使用angular并在ngOnInit()中初始化地图。

以下代码生成“InvalidValueError:setMap:not map 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图层?

angular google-maps kml
1个回答
0
投票

问题是初始化地图和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
    });
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.