close InfoWindow before open another

The suggestion is only create one infowindow (in the global scope), reuse it and change its contents when a marker is clicked, close it if the user clicks on the map.

code snippet (removes the dependency on the AJAX call):

// global variables
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("mappa_locali"), mapOptions);
  var json = JSON.parse(data);
  for (var i = 0; i < json.length; i++) {
    point = new google.maps.LatLng(json[i].latitudine, json[i].longitudine);
    var infowindowHtml="<a href="https://stackoverflow.com/questions/14321808/./dettaglioLocale.php?id_loc=" + json[i].id_locale + '">' + json[i].nome_locale + '</a><br>' + json[i].address;
    addMarkerz(point, infowindowHtml);
  }
}

function addMarkerz(point, infowindowHtml) {
  var marker = new google.maps.Marker({
    position: point,
    map: map
  });
  google.maps.event.addListener(marker, 'mouseover', infoCallback(infowindowHtml, marker));
  markers.push(marker);
}

function infoCallback(infowindowHtml, marker) {
  return function() {
    infowindow.close();
    // update the content of the infowindow before opening it
    infowindow.setContent(infowindowHtml)
    infowindow.open(map, marker);

  };
}


var data = JSON.stringify([{
  latitudine: 44.494887,
  longitudine: 11.3426163,
  id_locale: "0",
  nome_locale: "Bologna",
  address: "Bologna, Italy"
}, {
  latitudine: 44.4946615,
  longitudine: 11.314634999999953,
  id_locale: "0",
  nome_locale: "Quartiere Saragozza",
  address: "Quartiere Saragozza, Bologna, Italy"
}]);


google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#mappa_locali {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="mappa_locali"></div>

Leave a Comment