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

Issue

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

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);
 }

Answered By – Jane Dawson

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *