关闭infowindow自动谷歌地图

时间:2017-11-28 21:54:08

标签: google-maps

当打开另一个信息窗时,之前的信息保持打开状态。 如果我打开另一个信息窗口,如何自动关闭以前的信息窗口?我是新来的,你能帮助我吗?

  var map;
  var markers = [];  

  function initMap() {
    var cucuta = {lat: 7.9145395, lng: -72.505966};

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 14,
      center: cucuta,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    @foreach($users as $user)
      var ubicaciones = {lat: {{ $user->latitud }}, lng: {{ $user->longitud }} };
      var titulo = '{{ $user->name }}';
      addMarker(ubicaciones, titulo);
    @endforeach
  }

  function addMarker(location, titulo) {

      var marker = new google.maps.Marker({
      position: new google.maps.LatLng(location),
      map: map,
      title: titulo
    });
    markers.push(marker);

    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', (function(marker) {

      return function() {
        infowindow.setContent(titulo);
        infowindow.open(map, marker);
      }
    })(marker));
  }

  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  function showMarkers() {
    setMapOnAll(map);
  }

1 个答案:

答案 0 :(得分:0)

我刚试过这个in tryit,它按预期工作:

var map;
var infowindow;

function initMap() {
infowindow = new google.maps.InfoWindow();
var cucuta = {lat: 7.9145395, lng: -72.505966};

map = new google.maps.Map(document.getElementById('googleMap'), {
  zoom: 14,
  center: cucuta,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

addMarker({lat: 7.9145395, lng: -72.505966}, 'This is the info of <br>MAP1');
addMarker({lat: 7.9045395, lng: -72.505966}, 'This is the info of <br>MAP2');
}

function addMarker(location, titulo) {

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(location),
  map: map,
  title: titulo
});
marker.setMap(map);

google.maps.event.addListener(marker, 'click', function() {

  infowindow.setContent(titulo);
  infowindow.open(map, marker);
});
}