How can I hide infowindow on markers which are ins

2019-07-23 08:00发布

问题:

I am having few markers which have infowindow and markerclusters. I want to hide the infoWindow of the markers when they become part of marker clusters in the map and show tem when they are actually shown individually rather than in a cluster.

The code for markers and infowindow is something like:

    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
     ...         
    });



var myOptions = {
        .......
};

infowindow = new InfoBox(myOptions);
infowindow.open(map, marker);

markers.push(marker);

Then I have marker cluster

 var markerCluster = new MarkerClusterer(map, markers,markerClustererOptions);

Can someone provide code/suggestions/link on how to approach this

回答1:

Observe the map_changed-event of the markers. When the map-property of a marker is null, close the infowindow, otherwise open it.

       google.maps.event.addListener(marker,'map_changed',function(){
        if(this.getMap()){
          infowindow.open(this.getMap(),this);
        }
        else{
          infowindow.close();
        }
       });

Example:

function initialize() {


  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: new google.maps.LatLng(0, 0),

    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var markers = [];
  for (var i = 0; i < 100; i++) {
    (function(photo) {
      var latLng = new google.maps.LatLng(photo.latitude,
          photo.longitude),
        marker = new google.maps.Marker({
          position: latLng
        });
      console.log(photo)
      markers.push(marker);
      var infowindow = new InfoBox({
        content: '<img src="http://mw2.google.com/mw-panoramio/photos/thumbnail/' + photo.photo_id + '.jpg" />',
        disableAutoPan: true,
        closeBoxURL: "",
        pane: "floatPane"

      });

      google.maps.event.addListener(marker, 'map_changed', function() {
        if (this.getMap()) {
          infowindow.open(this.getMap(), this);
        } else {
          infowindow.close()
        }
      });


    }(data.photos[i]));

  }
  var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  margin: 0;
  padding: 0;
  height: 100%;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://googlemaps.github.io/js-marker-clusterer/examples/data.json"></script>
<script src="https://googlemaps.github.io/js-marker-clusterer/src/markerclusterer.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>