How could I call a Angular2 function from a Google Map infowindow?

后端 未结 5 1894
小鲜肉
小鲜肉 2021-02-10 17:17

Google map is integrated the javascript way and I want to call a angular2 function inside an infowindow like the following code. Take a look at infoContent for the

5条回答
  •  北海茫月
    2021-02-10 17:39

    You can do the trick instancing a reference to ngZone in root Window and call it from inside the infoWindow.

    First you need to get access to NgZone in constructor:

     constructor(public _ngZone: NgZone) {    }
    

    And then you can set a pointer back to your zone in window, on ngOnInit, constructor or somewhere, depending of your code:

        window["angularComponentRef"] = { component: this, zone: this._ngZone };
    

    Finally you can callback from infoWindow to your Angular function with zone.run like this:

        for (i = 0; i < locations.length; i++) {
            let locLatLng = new google.maps.LatLng(locations[i].latitude, locations[i].longitude);
            let infoContent: string = '';
    
            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));
    
        }
    

    And you can clean the function when needed to avoid polute the window namespace, on ngOnDestroy for example:

     window["angularComponentRef"] = null;
    

提交回复
热议问题