【问题标题】:Google Map API v3 ~ Simply Close an infowindow?Google Map API v3 ~ 只需关闭信息窗口?
【发布时间】:2011-02-26 03:10:49
【问题描述】:

试图简单地关闭一个信息窗口?

我已经有一组标记,所以这样的东西会很好。谢谢

MyMarkers[i].infowindow.close();

【问题讨论】:

  • 哇金徽章!这么多人看过这个。一定有很多人遇到同样的问题。

标签: javascript google-maps google-maps-api-3


【解决方案1】:

使用v3 API,您可以使用InfoWindow.close() 方法轻松关闭InfoWindow。您只需要保留对您正在使用的InfoWindow 对象的引用。考虑以下示例,它会打开一个 InfoWindow 并在 5 秒后关闭它:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
  <title>Google Maps API InfoWindow Demo</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 400px; height: 500px;"></div>

  <script type="text/javascript">
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: new google.maps.LatLng(-25.36388, 131.04492),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: 'An InfoWindow'
    });

    infowindow.open(map, marker);

    setTimeout(function () { infowindow.close(); }, 5000);
  </script>
</body>
</html>

如果每个Marker 都有一个单独的InfoWindow 对象,您可能需要考虑将InfoWindow 对象添加为Marker 对象的属性:

var marker = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker.infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

然后您将能够打开和关闭 InfoWindow,如下所示:

marker.infowindow.open(map, marker);
marker.infowindow.close();

如果你有一个标记数组,同样适用:

var markers = [];

marker[0] = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker[0].infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

// ...

marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();

【讨论】:

  • 很棒的解释
  • OOP 天才的疯狂! ;-) 谢谢!这为在每个/一些/一个标记上附加特殊信息打开了一百万扇门……并随时随地收集或更改它。 1.000 感谢您的绝妙主意!
【解决方案2】:

或者您可以共享/重用相同的 infoWindow 对象。 请参阅此 google demo 以供参考。

与演示相同的代码

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

【讨论】:

    【解决方案3】:

    我遇到了类似的问题。我只是在我的代码中添加了以下内容:

    closeInfoWindow = function() {
        infoWindow.close();
    };
    
    google.maps.event.addListener(map, 'click', closeInfoWindow);
    

    完整的js代码是(上面的代码从底部算起大约15行):

    jQuery(window).load(function() {
    if (jQuery("#map_canvas").length > 0){
        googlemap();
    }
    });
    
    function googlemap() {
    
    jQuery('#map_canvas').css({'height': '400px'});
    
    // Create the map 
    // No need to specify zoom and center as we fit the map further down.
    var map = new google.maps.Map(document.getElementById("map_canvas"), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      streetViewControl: false
    });
    
    // Create the shared infowindow with two DIV placeholders
    // One for a text string, the other for the StreetView panorama.
    var content = document.createElement("div");
    var title = document.createElement("div");
    var boxText = document.createElement("div");
    
    var myOptions = {
             content: boxText
            ,disableAutoPan: false
            ,maxWidth: 0
            ,pixelOffset: new google.maps.Size(-117,-200)
            ,zIndex: null
            ,boxStyle: { 
              background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
              ,opacity: 1
              ,width: "236px"
              ,height: "300px"
             }
            ,closeBoxMargin: "10px 0px 2px 2px"
            ,closeBoxURL: "http://kdev.langley.com/wp-content/themes/langley/images/close.gif"
            ,infoBoxClearance: new google.maps.Size(1, 1)
            ,isHidden: false
            ,pane: "floatPane"
            ,enableEventPropagation: false
    };
    
    
    var infoWindow = new InfoBox(myOptions);
    var MarkerImage = siteRoot+'images/house-web-marker.png';
    
    // Create the markers
    for (index in markers) addMarker(markers[index]);
    function addMarker(data) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data.lat, data.lng),
            map: map,
            title: data.title,
            content: data.html,
            icon: MarkerImage
        });
        google.maps.event.addListener(marker, "click", function() {
            infoWindow.open(map, this);         
            title.innerHTML = marker.getTitle();
            infoWindow.setContent(marker.content);
            infoWindow.open(map, marker);
            jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});            
        });
    }
    
    // Zoom and center the map to fit the markers
    // This logic could be conbined with the marker creation.
    // Just keeping it separate for code clarity.
    var bounds = new google.maps.LatLngBounds();
    for (index in markers) {
        var data = markers[index];
        bounds.extend(new google.maps.LatLng(data.lat, data.lng));
    }
    map.fitBounds(bounds);
    var origcent = new google.maps.LatLng(map.getCenter());
    // Handle the DOM ready event to create the StreetView panorama
    // as it can only be created once the DIV inside the infowindow is loaded in the DOM.
    
    closeInfoWindow = function() {
            infoWindow.close();
        };
    
    google.maps.event.addListener(map, 'click', closeInfoWindow);
    
    google.maps.event.addListener(infoWindow, 'closeclick', function()
    {
        centermap();
    });
    
    function centermap()
    {
        map.setCenter(map.fitBounds(bounds));
    }
    }
    
    jQuery(window).resize(function() {
    googlemap();
    });
    

    【讨论】:

    • 此代码中似乎缺少某些内容。生成的地图显示空的信息窗口。
    • @husayt 这是一个相当古老的答案,我确信技术在过去 3 年中发生了变化。此外,代码需要根据您自己的目的进行配置。
    【解决方案4】:
    infowindow.open(null,null);
    

    将关闭打开的信息窗口。 它的工作原理与

    【讨论】:

    • 同什么?你忘了说完你的句子吗?
    【解决方案5】:

    您可以在创建 InfoWindow 的函数内的地图上简单地添加一个点击侦听器

    google.maps.event.addListener(marker, 'click', function() {
        var infoWindow = createInfoWindowForMarker(marker);
        infoWindow.open(map, marker);
        google.maps.event.addListener(map, 'click', function() {
            infoWindow.close();
        });
    });
    

    【讨论】:

      【解决方案6】:

      这个也可以:

      google.maps.event.addListener(marker, 'click', function() {
                      if(!marker.open){
                          infowindow.open(map,marker);
                          marker.open = true;
                      }
                      else{
                          infowindow.close();
                          marker.open = false;
                      }
                  });
      

      点击它会打开一个信息窗口,如果它是打开的,点击它时关闭它。

      也看过Logan的解决方案,这两个可以合并成这样:

      google.maps.event.addListener(marker, 'click', function() {
                      if(!marker.open){
                          infowindow.open(map,marker);
                          marker.open = true;
                      }
                      else{
                          infowindow.close();
                          marker.open = false;
                      }
                      google.maps.event.addListener(map, 'click', function() {
                          infowindow.close();
                          marker.open = false;
                      });
                  });
      

      点击它会打开一个信息窗口,点击它并打开它时关闭它,如果点击地图上的任何地方并打开信息窗口则关闭它。

      【讨论】:

        【解决方案7】:

        即使在使用多个标记和信息窗口时,以下事件侦听器也为我很好地解决了这个问题:

        //Add click event listener
        google.maps.event.addListener(marker, 'click', function() {
          // Helper to check if the info window is already open
          google.maps.InfoWindow.prototype.isOpen = function(){
              var map = infoWindow.getMap();
              return (map !== null && typeof map !== "undefined");
          }
          // Do the check
          if (infoWindow.isOpen()){
            // Close the info window
            infoWindow.close();
          } else {
            //Set the new content
            infoWindow.setContent(contentString);
            //Open the infowindow
            infoWindow.open(map, marker);
          }
        });
        

        【讨论】:

          【解决方案8】:

          我们可以使用 infowindow.close(map);如果您已经使用 infowindow = new google.maps.InfoWindow(); 初始化信息窗口,则关闭所有信息窗口;

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-31
            • 1970-01-01
            • 2012-09-16
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多