close InfoWindow before open another

前端 未结 3 1174
终归单人心
终归单人心 2020-11-27 23:48

I have a problem with InfoWindow. I have an ajax function that retrieves data via JSON, but I can not get close InfoWindow automatically when you open another. My code is th

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 00:17

    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 = '' + json[i].nome_locale + '
    ' + 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
    }
    
    

提交回复
热议问题