C
C
Cheizer2018-07-10 20:49:55
Google
Cheizer, 2018-07-10 20:49:55

Google Map API Why same content in infowindow?

Friends, I broke my head, tell me please, why is there the same content in infowindow ???

I initialize the Google map like this, there are two markers with their addresses. At the end of the cycle with adding markers and their infowindow, the markers are placed correctly, but the information "Address 1" and "Address 2" is wrong, for both markers on click it shows "Address 1", what did you do wrong? Where to dig?

function initialize() {  
              var myLatLng = {lat: 55.7319, lng: 37.6145};
    var myMapOptions = {
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    zoom: 11,
                    scrollwheel: false,
                    mapTypeControl: false,
                    zoomControl: true,
          //draggable: draggable,
          styles: [{"stylers": [{ "saturation": -100 }]}],
        };
                var map = new google.maps.Map(document.getElementById("map"), myMapOptions);
              var locations = [
          {
            position: {lat: 55.6709, lng: 37.7475},
            icon: {
              url: "/images/pinMap.png",
              scaledSize: new google.maps.Size(69, 69)
            },
                        popupContent: '<p class="contentmap">Адрес 1</p>',
          },
          {
            position: {lat: 55.7015, lng: 37.8497},
            icon: {
              url:"/images/pinMap.png",
              scaledSize: new google.maps.Size(69, 69)
            },
                        popupContent: '<p class="contentmap">Адрес 2</p>',
          }];
    
    	      locations.forEach( function( element, index ){

          var marker = new google.maps.Marker({
            position: element.position,
            map: map,
            icon: element.icon,
          });
                  
       infowindow = new google.maps.InfoWindow({
            content: element.popupContent
        });        
       marker.addListener('click', function () {
          infowindow.open(map, marker);
       });       
});	
      }


There is a suspicion that I am not calling marker.addListener correctly, but this is not a fact :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Formula_1, 2018-07-10
@Cheizer

Changed foreach to for and declared variables via let:

for (let i = 0; i < locations.length; i++) {
  let marker = new google.maps.Marker({
    position: locations[i].position,
    map: map,
  });

  let infowindow = new google.maps.InfoWindow({
    content: locations[i].popupContent
  });

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question