我如何从Google Map infowindow调用Angular2函数?

Ale*_*idt 3 javascript google-maps-api-3 google-maps-markers angular

谷歌地图是以javascript方式集成的,我想在infowindow中调用angular2函数,如下面的代码.看看infoContent按钮.

for (i = 0; i < locations.length; i++) {

  let locLatLng = new google.maps.LatLng(locations[i].latitude, locations[i].longitude);
  let infoContent = '<button (click)="myFunction(' + locations[i].id + ')">Details ...</button>';

  marker = new google.maps.Marker({
    position: locLatLng,
    map: this.map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(infoContent);
      infowindow.open(this.map, marker);
    };
  })(marker, i));

}
Run Code Online (Sandbox Code Playgroud)

不幸的是,角点击事件(click)="myFunction()"无法做到.必须有另一种方式.如果有人能指出我正确的方向,我会很高兴.提前致谢.

小智 7

您可以在根窗口中实例化对ngZone的引用,并从infoWindow内部调用它.

首先,您需要在构造函数中访问NgZone:

 constructor(public _ngZone: NgZone) {    }
Run Code Online (Sandbox Code Playgroud)

然后你可以在窗口,ngOnInit,构造函数或某个地方设置指向你的区域的指针,具体取决于你的代码:

    window["angularComponentRef"] = { component: this, zone: this._ngZone };
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用zone.run从infoWindow回调到Angular函数,如下所示:

    for (i = 0; i < locations.length; i++) {
        let locLatLng = new google.maps.LatLng(locations[i].latitude, locations[i].longitude);
        let infoContent: string = '<button onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.myFunction(\'' + locations[i].id + '\');})">Details ...</button>';

        marker = new google.maps.Marker({
            position: locLatLng,
            map: this.map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(infoContent);
                infowindow.open(this.map, marker);
            };
        })(marker, i));

    }
Run Code Online (Sandbox Code Playgroud)

并且你可以在需要时清理函数以避免在ngOnDestroy上对窗口命名空间进行轮询,例如:

 window["angularComponentRef"] = null;
Run Code Online (Sandbox Code Playgroud)