简体   繁体   中英

Why don't other infowindows hide when a new infowindo shows up in my code?

I've been adding google map with markers and infowindows. I made the following code:

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Info windows</title>
  <style>
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #map {
      height: 100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <script>

      // This example displays a marker at the center of Australia.
      // When the user clicks the marker, an info window opens.

      function initMap() {
        var uluru = {lat: -25.363, lng: 131.044};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });

        var contentString = [];
        contentString[0] = '<div id="content">'+
        '<div id="siteNotice">'+
        '</div>'+
        '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
        '<div id="bodyContent">'+
        '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
        'sandstone rock formation in the southern part of the '+
        'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) '+
        'south west of the nearest large town, Alice Springs; 450&#160;km '+
        '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major '+
        'features of the Uluru - Kata Tjuta National Park. Uluru is '+
        'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
        'Aboriginal people of the area. It has many springs, waterholes, '+
        'rock caves and ancient paintings. Uluru is listed as a World '+
        'Heritage Site.</p>'+
        '<p>Attribution: Uluru, <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
        'https://en.wikipedia.org/w/index.php?title=Uluru</a> '+
        '(last visited June 22, 2009).</p>'+
        '</div>'+
        '</div>';

        contentString[1] = '<div id="content">'+
        '<div id="siteNotice">'+
        '</div>'+
        '<h1 id="firstHeading" class="firstHeading">New York</h1>'+
        '<div id="bodyContent">'+
        '<p><b>New York</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
        'sandstone rock formation in the southern part of the '+
        'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) '+
        'south west of the nearest large town, Alice Springs; 450&#160;km '+
        '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major '+
        'features of the Uluru - Kata Tjuta National Park. Uluru is '+
        'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
        'Aboriginal people of the area. It has many springs, waterholes, '+
        'rock caves and ancient paintings. Uluru is listed as a World '+
        'Heritage Site.</p>'+
        '<p>Attribution: Uluru, <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
        'https://en.wikipedia.org/w/index.php?title=Uluru</a> '+
        '(last visited June 22, 2009).</p>'+
        '</div>'+
        '</div>';



        var markers = [];

        markers[0] = new google.maps.Marker({
          position: uluru,
          map: map,
          title: 'Uluru (Ayers Rock)'
        });
        markers[1] = new google.maps.Marker({
          position: {lat: -20.363, lng: 120.044},
          map: map,
          title: 'New York'
        });
        function setwindow(i) {
          var infowindow = new google.maps.InfoWindow({
            content: contentString[i],
            maxWidth: 200
          });
          markers[i].addListener('click', function() {          
            infowindow.open(markers[i].get('map'), this);
          });
        }

        for (var i = markers.length - 1; i >= 0; i--) {
         setwindow(i);
        }








      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBga3chd-auBMGLGITc3rjact16mozcI4Q&callback=initMap">
  </script>
</body>
</html>

As you can see I have used only one infowindow variable. But when one infowindow is open and we click on other marker the previous infowindow doesn't hide. Both the new and old infowindow show up.

Google API's official page says:

For the best user experience, only one info window should be open on the map at any one time. Multiple info windows make the map appear cluttered. If you only need one info window at a time, you can create just one InfoWindow object and open it at different locations or markers upon map events, such as user clicks. If you do need more than one info window, you can display multiple InfoWindow objects at the same time.

This is exactly what I am doing. I have only one infowindow variable. So,

Why don't other infowindows hide when a new infowindow shows up in my code?

From the answers it seems that each time the for loop runs it creates new infowindow objects without overriding the previous one. I thought when the loop runs for the second time the first infowindow object is just overridden

How can there be more than one infowindow objects with the same name?

Google API using infowindow Class to overlay some content on given marker or LatLong. In you example, setwindow function is responsible for associating infowindow object with Map UI and setting up content.

By looping this operation, JavaScript object once drawn on Map is now associated with it and if you re-initializing infowindow object(not Map drawn reference), it will be redrawn on Map. ( Function Scoping )

Instead, you should create infowindow object with empty content:

var markers = [];
var infowindow = new google.maps.InfoWindow({
     content: "",
     maxWidth: 200
});

And in setwindow function, you should set content only:

function setwindow(i) {
      markers[i].addListener('click', function() { 
         infowindow.setContent(contentString[i]); 
         infowindow.open(markers[i].get('map'), this);
      });
    }

Google API's official page clearly states it as Best practices: only one info window should be open on the map at any one time

Because you are constructing infowindows for each markers. You should do something like this:

 ...
    var markers = [];

    markers[0] = new google.maps.Marker({
      position: uluru,
      map: map,
      title: 'Uluru (Ayers Rock)'
    });
    markers[1] = new google.maps.Marker({
      position: {lat: -20.363, lng: 120.044},
      map: map,
      title: 'New York'
    });

    var infowindow = new google.maps.InfoWindow({maxWidth: 200});
    function setwindow(i) {
      markers[i].addListener('click', function() {          
        infowindow.setContent(contentString[i]);
        infowindow.open(markers[i].get('map'), this);
      });
    }

    for (var i = markers.length - 1; i >= 0; i--) {
     setwindow(i);
    }
 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM