No Repeat Values

2

I'm using google maps api and I'm kind of a layman in js. My map displayed markers and on each marker I will display an infowindow or an information balloon. The code below is doing this, but is repeating Array values, how do I display the specific value of each marker or location?

for(var i = 0; i<cord.length; i++){
       var contentString = cord[i].local;
        /*var infowindow = new google.maps.InfoWindow({
    //content: contentString
  });*/

        //var location = cord.latlong[i].split(",");
        var marker = new google.maps.Marker({
        position: new google.maps.LatLng(cord[i].lat, cord[i].long),
        map: map
    });
        google.maps.event.addListener(marker, 'mouseover', function() { 
           
        infowindow.setContent(contentString);
        infowindow.open(map, this);
        });
       
    }
    
asked by anonymous 25.11.2016 / 13:07

1 answer

1

The problem is that you are overwriting the variable in loop .

One solution would be to store the name in every marker :

   marker.contentString = cord[i].local;

And retrieve the value with this :

    infowindow.setContent(this.contentString);

Applied to code:

for(var i = 0; i<cord.length; i++){
        var marker = new google.maps.Marker({
        position: new google.maps.LatLng(cord[i].lat, cord[i].long),
        map: map
    });

    google.maps.event.addListener(marker, 'click', function() { 
        infowindow.setContent(this.contentString);
        infowindow.open(map, this);
    });

    marker.contentString = cord[i].local;
    console.log(cord[i]);
}

See working at CODEPEN .

    
25.11.2016 / 14:14