本文介绍了单击时关闭所有其他InfoWindows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图修改下面的代码,以便所有其他infoWindows在单击时关闭,所以只有一个是一次打开的。除了用户最多可以打开20个infoWindows之外,目前所有的工作都很棒。

   


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);
});
}
解决方案

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>

这篇关于单击时关闭所有其他InfoWindows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 19:23