Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Close all infowindows in Google Maps API v3

I am busy with a script that will make a google maps canvas on my website, with multiple markers. I want that when you click on a marker, a infowindow opens. I have done that, and the code is at the moment:

 var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    function addMarker(map, address, title) {
     geocoder = new google.maps.Geocoder();
     geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
     position: results[0].geometry.location,
              map: map,
              title:title
    });
    google.maps.event.addListener(marker, 'click', function() {
     var infowindow = new google.maps.InfoWindow();
            infowindow.setContent('<strong>'+title + '</strong><br />' + address);
             infowindow.open(map, marker);

          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
     });
    }
    addMarker(map, 'Address', 'Title');
 addMarker(map, 'Address', 'Title');

This works 100%. But now i want that when one infowindow is open, and you want to open the second, the first one automaticly closes. But i haven't found a way to do that. infowindow.close(); won't help. Has someone an example or a solution to this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

infowindow is local variable and window is not available at time of close()

var latlng = new google.maps.LatLng(-34.397, 150.644);
var infowindow = null;

...

google.maps.event.addListener(marker, 'click', function() {
    if (infowindow) {
        infowindow.close();
    }
    infowindow = new google.maps.InfoWindow();
    ...
});
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...