How to set a popup on markers with Google Maps API?

Viewed 55907

I have this code where I display and set all my markers. How can I add a popup with some information on markers with this code? I add "i" variable on text, but it sets on all markers popup with "test - 723", where 723 is last value of the "i" variable. What is wrong?

for (var i = 0; i < arraylng.length-1; i++) {
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(arraylng[i], arraylat[i])
  });
  var infowindow = new google.maps.InfoWindow({
    content: " "
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent('test: ' + i + '');
    infowindow.open(map, this);
  });
  markers.push(marker);
}
4 Answers

this is the area where you can add your content of popup

var infowindow = new google.maps.InfoWindow({
                content: "Add your popup content here"
              });

and this is for showing your popup

marker.addListener('click', function() {
          infowindow.open(map, marker);
        });

Below code shows how its work and use.

features.forEach(function(feature) {
          var infowindow = new google.maps.InfoWindow({
                    content: "Add your popup content here"
                  });
            var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat,long),
            icon: "image.png",
            /*icon: icons[feature.type].icon,*/
            title: "Title for marker",
            map: map
          });
          marker.addListener('click', function() {
          infowindow.open(map, marker);
        });
        });

Related