Trần Minh Phương
Trần Minh Phương

Reputation: 329

How to close POI's InfoWindow?

I'm trying to make POI's InfoWindow close when click a link.

I overrided the setContent of InfoWindow like this:

//override the built-in setContent-method
google.maps.InfoWindow.prototype.setContent = function (content) {              
    content = content.innerHTML + '<br/> <a href="#" onclick="onSavePlace();">Save place</a>';
    //run the original setContent-method
    fx.apply(this, arguments);
};

Note: I didn't create any InfoWindow object to reference to use close() method.

Upvotes: 2

Views: 462

Answers (1)

geocodezip
geocodezip

Reputation: 161324

In your override function capture a global reference to the infowindow so you can reference it to close it.

Your override of the infowindow doesn't work. I took a working version from this question: How to get a click event when a user clicks a (business) place on the map

proof of concept fiddle

code snippet:

var geocoder;
var map;
var infowindow;

//keep a reference to the original setPosition-function
var fx = google.maps.InfoWindow.prototype.setPosition;

// from https://stackoverflow.com/questions/24234106/how-to-get-a-click-event-when-a-user-clicks-a-business-place-on-the-map/24234818#24234818
//override the built-in setPosition-method
google.maps.InfoWindow.prototype.setPosition = function() {
  //logAsInternal isn't documented, but as it seems
  //it's only defined for InfoWindows opened on POI's
  if (this.logAsInternal) {

    // save reference in global infowindow variable.
    infowindow = this;

    google.maps.event.addListenerOnce(this, 'map_changed', function() {
      var map = this.getMap();
      //the infoWindow will be opened, usually after a click on a POI
      if (map) {
        //trigger the click
        google.maps.event.trigger(map, 'click', {
          latLng: this.getPosition()
        });
      }
    });
  }
  //call the original setPosition-method
  fx.apply(this, arguments);
};

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  google.maps.event.addDomListener(document.getElementById('btn'), 'click', function(e) {

    // close the last opened POI infowindow
    infowindow.close();

  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="btn" type="button" value="close IW" />
<div id="map_canvas"></div>

Upvotes: 1

Related Questions