如何在谷歌地图中关闭InfoWindow时缩小地图?

时间:2016-08-17 09:26:21

标签: javascript google-maps

我想在InfoWindow关闭时缩小地图。我试过这个。

 google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.open(map);
            map.panTo(this.getPosition());
            map.setZoom(6);
        }

    })(marker, i));

    google.maps.event.addListener(marker, 'closeclick', (function(marker, i){
        return function() {
                 map.panTo(this.getPosition());
                 map.setZoom(2);
        }
    })(marker, i));

但它不起作用。谁能帮我!! 在我的地图中有一些标记,当单击一个标记时,它将放大到该位置,我想在InfoWindow关闭时应用缩小。

1 个答案:

答案 0 :(得分:0)

google.maps.Marker没有' closeclick'事件,您需要在InfoWindow上听取该事件。

google.maps.event.addListener(infoWindow, 'closeclick', function() {
  map.panTo(this.getPosition());
  map.setZoom(2);
});

proof of concept fiddle

代码段



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 marker = new google.maps.Marker({
    map: map,
    position: map.getCenter()
  });
  var infoWindow = new google.maps.InfoWindow();
  var infoWindowContent = [];
  infoWindowContent[0] = ["test"];
  var i = 0;
  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infoWindow.setContent(infoWindowContent[i][0]);
      infoWindow.open(map, marker);
      map.panTo(this.getPosition());
      map.setZoom(6);
    }

  })(marker, i));

  google.maps.event.addListener(infoWindow, 'closeclick', function() {
    map.panTo(this.getPosition());
    map.setZoom(2);
  });
}
google.maps.event.addDomListener(window, "load", initialize);

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>
&#13;
&#13;
&#13;