BRass
BRass

Reputation: 3838

Google Maps InfoWindow - (click) trigger an Angular 2 function

I have a component that leverages google maps in an Angular 2+ app. Is there a decent way to get a link into a marker's infowindow that will trigger a method in my component? The (click) below is the trouble spot. I can swap to onclick if I want to mess with making a global method (hoping to avoid that).

//Add directions if we have a current location
let additionalContent = "";
if(this.positionMarker){
  additionalContent = `<br><a href='#' (click)='startNavigating(${marker.position.lat()}, ${marker.position.lng()})'>Directions</a>`;
}

let infoWindow = new google.maps.InfoWindow({
  content: content + additionalContent
});

google.maps.event.addListener(marker, 'click', () => {
  infoWindow.open(this.map, marker);
});

Upvotes: 1

Views: 3046

Answers (1)

BRass
BRass

Reputation: 3838

Found a few pieces to make this work without crazy angular overhead. The keys were to:

  1. Only have 1 info window (member)
  2. Add unique IDs to the anchor tags
  3. When the infoWindow opens (domready), add a click listener to the anchor's id that was clicked

Code below:

//Add directions if we have a current location
let additionalContent = "";
if (this.positionMarker) {
  additionalContent = `<br><a href='#' id='marker_${markerId}'>Directions</a>`;
}

//Add the marker listener to open the infowindow
google.maps.event.addListener(marker, 'click', () => {
  this.infoWindow.setContent(content + additionalContent);
  this.infoWindow.open(this.map, marker);

  //Once infow window is open, add a click listener based on the ID in the anchor tag
  if (additionalContent) {
    google.maps.event.addListenerOnce(this.infoWindow, 'domready', () => {
      document.getElementById(`marker_${markerId}`).addEventListener('click', () => {
        this.startNavigating(marker.position.lat(), marker.position.lng());
      });
    });
  }
});

Upvotes: 3

Related Questions