Do Not Repeat Values

Asked

Viewed 100 times

2

I’m using google maps api and I’m kind of a layman at js. My map shows markers and in each marker I will display an infowindow or information balloon. The code below is doing this, but is repeating the values of the Array, as I display the specific value of each marker or locale?

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);
        });
       
    }

  • The repeated value is in contentString ?

  • gives a console.log(i) and shows me output, please

  • contentString is actually receiving each array value. The output of i is 0 and 1 which are the two objects of the array In the case: var Cord = [{ "lat":"-19.45738", "long":"-44.2416695", "local":"Cidade1" }, { "lat":"-15.7942287", "long":"-48.0783226", "local":"Cidade2" }];

  • You are using the same value for everyone, sure will always be the last of the loop.

  • @Bacco how I fix this?

  • You need to assign a value to each marketer separately instead of playing in a single variable.

  • @Bacco Opa, sorry: http://codepen.io/anon/pen/YpQgeR

Show 2 more comments

1 answer

1


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

A solution would be to store the name in each marker:

   marker.contentString = cord[i].local;

And reclaim the value with this:

    infowindow.setContent(this.contentString);

Applied to the 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 on CODEPEN.

  • Perfect, thank you @Bacco

Browser other questions tagged

You are not signed in. Login or sign up in order to post.