The Google Maps documentation describes an example of opening a single info window for one marker:

var infowindow = new google.maps.InfoWindow({ content: contentString }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Uluru (Ayers Rock)" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); 

I need to put a lot of markers on the map so that each has its own info window with data from my previously prepared array. However, a simple change of the marker , infowindow to the marker[] , infowindow[] arrays in a loop did not give the desired result. Clicking on any marker crashes the info window of the last set marker. Tell me where to look for an error or an example for such a task.

    2 answers 2

    My rating has grown, so I had the opportunity to respond to myself. So:

      var marker = new google.maps.Marker ({ 
              position: myCenter, 
              map: map, 
              title: 'Object:' + devices [i] [1],
              icon: image}); 
              // devices [] is a previously prepared array with complete information on each object, i is a counter in the loop, the other variables are also defined initially
           mArray.push (marker);
           mArray [i] .setMap (map);  // markers are stored for selective processing (optional)
           makeInfoWin (marker, html);  // html - pre-prepared text in the form of HTML markup, which will be displayed in the current info window
           }
     } 
    function makeInfoWin (marker, data) { var infowindow = new google.maps.InfoWindow ({content: data}); google.maps.event.addListener (marker, 'click', function () { infowindow.open (map, marker); });
    }
    API v.3

      Thank you very much! However, when inserting this code, an error occurred in the function makeInfoWin , namely, undefined var "map" , I had to finish writing it a bit, passing it to the corresponding. parameter.

      Call line:

       makeInfoWin(marker, html, map); function makeInfoWin(marker, data, map) { // добавили map var infowindow = new google.maps.InfoWindow({ content: data }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } 
      • map is a global variable, it is announced once at the beginning of the code, as in all examples from the Google Maps API v3.0 Samples, what you have written will create a new map on each call, which will waste resources. - deivan_