Prevent Google maps infowindow from closing

2019-09-17 11:30发布

问题:

If certain conditions are met when an infoWindow is closed, I want to prevent the default close event that is fired. Is it possible to achieve that? I tried a number of things like:

  1. Stopping event propagation
  2. returning false from the callback method
  3. there aren't any methods/properties exposed by the infoWindow either that prevent close.

Please let me know if this is possible.

回答1:

The InfoWindow doesn't really provide a way to step event propagation. I don't know if it could work for you, but there is an InfoBox Utility Library that does give you a great deal more of control oven its behavior. Specific to your question, the InfoBoxOptionsapi-doc object includes the property:

enableEventPropagation, a boolean, that will allow you to control whether the InfoBox will: propagate mousedown, click, dblclick, and contextmenu events in the InfoBox (default is false to mimic the behavior of a google.maps.InfoWindow). Set this property to true if the InfoBox is being used as a map label. iPhone note: This property setting has no effect; events are always propagated.



回答2:

The only thing you can do is catch the closeclick event which leads you nowhere.

I have hacked something together once, for a one-off solution, that might or might not work for you: I have identified a way to get to the x-mark that the user clicks to close, and removed that. The user can't close the infoWindow. At all. You still can, by calling .close().

WARNING! THIS IS A HACK

var a=document.getElementById('map_canvas');
var b=a.getElementsByTagName('img');
var i, j=b.length;
for (i=0; i<j; i++) {
  if(b[i].src.match('imgs8.png')){
    if(b[i].style.left=='-18px') {
      c=b[i].parentElement.parentElement;
      console.log(c);
      if(c.innerText.match("Map data")) {
        console.log('no');
      } else {
        b[i].parentElement.removeChild(b[i]);
      }
    }
  }
}

Now. If you store a reference to the [x] mark, you could even turn it on and off at will.

EDIT:

A demonstration of this hack



回答3:

You could always listen for the close event and then throw a javascript error to keep it from closing. Ex:

google.maps.event.addListener(my_infoWindow, 'closeclick', function(e){
    // Throw an error to stop the close
    throw "stop close";
})