'Button in google maps information window with access to the page's functions

I'm developing an Angular2 / Ionic 2 mobile App and using the google maps JS API to show markers on a map. When clicking on a marker, an information window opens. Inside this information window I have a text and a button. I call a function when the button is clicked. If this function just does a console.log everything works as expected.

However, I got a problem regarding the scope, I think. When clicking the button, I don't get it running to access any function of the page or calling the NavController to move to another Page.

addInfoWindow(marker, origContent){

    let infoWindow = new google.maps.InfoWindow();

    var content = document.createElement('div');
    content.innerHTML = (origContent);
    var button = content.appendChild(document.createElement('input'));
    button.type = 'button';
    button.id = 'showMoreButton';
    button.value = 'show more';
    google.maps.event.addDomListener(button, 'click', function () {
      request();
      // this works. the method "request()" is called on a click on the button
    });

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(content);
    });


    function request() {

      this.navCtrl.push(RequestPage);
      // this does not work (scope reasons?). I can't access any method or component of my page.
    }

  }

What do I have to do to be able to access the NavController for example? I tried so many different things, incl. NgZone, but didn't get it running...



Solution 1:[1]

Found the solution. It's so easy. I can access a function of my page using "bind" like this:

button.addEventListener('click', this.request.bind(this, variable1));
// calls the function "request(variable1)"

Full context:

addInfoWindow(marker, origContent){
    let infoWindow = new google.maps.InfoWindow();

    var content = document.createElement('div');
    content.innerHTML = (origContent);
    var button = content.appendChild(document.createElement('input'));
    button.type = 'button';
    button.id = 'showMoreButton';
    button.value = 'show more';
    button.addEventListener('click', this.request.bind(this, resultsOneUser));

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(content);
    });
  }

function request() {
   this.navCtrl.push(RequestPage);
 }

Solution 2:[2]

Using Ionic/Capacitor and Angular I needed a solution to bind a click event to a custom button added to a Google map that was NOT a marker or an infoWindow.

It took me a while to find this, way longer than it should've for such a simple thing, but this is the way (at least for me and my issue).

button.addEventListener('click', this.request.bind(this, resultsOneUser));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jane Dawson
Solution 2 jps