【问题标题】:Initializing google map with kml layer using Angular: InvalidValueError: setMap: not an instance of Map使用 Angular 使用 kml 层初始化谷歌地图:InvalidValueError: setMap: not an instance of Map
【发布时间】:2018-03-06 15:39:42
【问题描述】:

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

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

【问题讨论】:

    标签: angular google-maps kml


    【解决方案1】:

    问题在于初始化地图,以及 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
        });
      }
    
    }
    

    【讨论】:

    • 变量gmapElement,它是什么类型的?为什么要返回 ngOnInit?我问你这个是因为我无法重现你指出的例子。
    • @drielnox 几年后看这个,看起来我只是不明白国家是如何运作的哈哈!不知道为什么我会把那个 return 声明放在那里,除了我不知道我在做什么。你遇到了什么问题?
    • 这是一个与这里讨论的问题非常相似的问题。经过深入研究,我注意到 Angular 的 Google Maps 组件并没有在 NPM 包中实现 KML 层的 API。您可以通过在 JS 和 TS 之间进行混合实现来实现放置 KML 层,但这正是我想要避免的。此外,获取实例化 KmlLayer 所需的 Map 非常困难,因为 GoogleMap 对象(请参阅文档)没有获取原生 HTML 元素的属性或其他东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多