Search code examples
javascriptgoogle-maps-api-3infowindow

Call function for content of infowindow when opening not only on init


I have some objects with markers. These objects have dynamic data and I would like to output them in the infowindow of the marker of the object. So far this is what I have:

function createRandomObjectWithAMarker() {
  var marker;
  var aData = "dataToDisplay";
  var infowindow = new google.maps.InfoWindow({
    content:callThisFunctionWhenOpenWindow(aData)
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
  randomObject = {
    /*
    someData
    */
    marker: marker
  };
  return randomObject;
}

And I would like that this function to be called when I click the marker to show the return modifiedData as the content of the infoWindow.

function callThisFunctionWhenOpenWindow(aData){
  /*
  do some stuff on aData
  */
  return modifiedData;
}

But actually, this function is called once: only when I init the randomObject with the call of createRandomObjectWithAMarker(). So if I show the infoWindow after some time, when the datas would not be the same as when the script starter, it will still display the same output. Is there any way to do that? If yes how?


Solution

  • Try something like this?

    This way the infowindow (and it's data) is only created when you click the marker

    function createRandomObjectWithAMarker() {
      var marker;
      var aData = "dataToDisplay";
      marker.addListener('click', function() {
        var infowindow = new google.maps.InfoWindow({
          content:callThisFunctionWhenOpenWindow(aData)
        });
        infowindow.open(map, marker);
      });
      randomObject = {
        /*
        someData
        */
        marker: marker
      };
      return randomObject;
    }