Close all other InfoWindows when one is clicked

空扰寡人 提交于 2020-01-24 21:55:07

问题


I am trying to amend the below code so that all other infoWindows are closed when one is clicked, so only one is open at once. All currently works great, besides the fact that the user can open up to 20 infoWindows. Thanks for your help.

function infoWindow(marker, map, title, address, url) {
 google.maps.event.addListener(marker, 'click', function () {
  var html = "<div><h3>" + title + "</h3><p><a href='" + url + "'>Read More</a></p></div>";
    iw = new google.maps.InfoWindow({
        content: html,
        maxWidth: 350
    });
    iw.open(map, marker);
});
}

回答1:


If you only want one InfoWindow, only create one and move it between markers on the click event.

updated code:

// global infowindow
var iw = new google.maps.InfoWindow({
  maxWidth: 350
});

function infoWindow(marker, map, title, address, url) {
  google.maps.event.addListener(marker, 'click', function() {
    var html = "<div><h3>" + title + "</h3><p><a href='" + url + "'>Read More</a></p></div>";
    // set the content (saved in html variable using function closure)
    iw.setContent(html);
    // open the infowindow on the marker.
    iw.open(map, marker);
  });
}

proof of concept fiddle

code snippet:

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var marker1 = new google.maps.Marker({
    position: new google.maps.LatLng(37.4419, -122.1419),
    map: map
  });
  infoWindow(marker1, map, "title1", "address1", "http://www.google.com")
  var marker2 = new google.maps.Marker({
    position: new google.maps.LatLng(37.44, -122.14),
    map: map
  });
  infoWindow(marker2, map, "title2", "address2", "http://www.yahoo.com")


}
google.maps.event.addDomListener(window, "load", initialize);
// global infowindow
var iw = new google.maps.InfoWindow({
  maxWidth: 350
});

function infoWindow(marker, map, title, address, url) {
  google.maps.event.addListener(marker, 'click', function() {
    var html = "<div><h3>" + title + "</h3><p><a href='" + url + "' target='_blank'>Read More</a></p></div>";
    // set the content (saved in html variable using function closure)
    iw.setContent(html);
    // open the infowindow on the marker.
    iw.open(map, marker);
  });
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>


来源:https://stackoverflow.com/questions/38569860/close-all-other-infowindows-when-one-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!