Google map close info window when another marker is clicked

后端 未结 1 620
说谎
说谎 2021-01-28 17:21

I know there are lots of questions related to my one. But i have seen almost all of them and tried to apply some of them. But nothing happens. Below is my code

          


        
相关标签:
1条回答
  • 2021-01-28 17:42

    Don't create the infowindow within the loop. You only need one object and set its content depending on which marker you click.

    You also need to use a closure around your marker click listener. Something like that:

    google.maps.event.addListener(marker, 'click', (function(marker) {
    
      return function() {
    
        // Something here
      }
    
    })(marker));
    

    Working example below.

    function initialize() {
    
      var mapOptions = {
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(1, 1)
      };
    
      var locations = [
        [new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
        [new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
        [new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
        [new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
        [new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
        [new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
      ];
    
      var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    
      var infowindow = new google.maps.InfoWindow();
    
      $.each(locations, function(i, item) {
    
        var marker = new google.maps.Marker({
          position: item[0],
          map: map,
          title: item[1],
        });
    
        google.maps.event.addListener(marker, 'click', (function(marker) {
    
          return function() {
            infowindow.setContent(item[2]);
            infowindow.open(map, marker);
          }
    
        })(marker));
      });
    
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    #map-canvas {
      height: 150px;
    }
    <div id="map-canvas"></div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

    0 讨论(0)
提交回复
热议问题