1

here's my code:

function myMap() {

var sensorID = [];   //Sensor ID array

//More Code

for (var i = 0; i<sensorID.length; i++){
    sensorNodes[i] = new google.maps.LatLng(sensorLatitude[sensorID[i]], sensorLongitude[sensorID[i]]); //No problem here

    marker[i] = new google.maps.Marker({ position:sensorNodes[i] }); //No problem here

    google.maps.event.addListener(
        marker[i],'click',function(){
        infowindow.setContent("Sensor ID: " + sensorID[i]);
        infowindow.open(map,this);
        }
    );
}

In that last block of code, the function nested inside the addListener is supposed to open a box that says Sensor ID: #

However, there's a problem with SensorID[i] inside that function. The code won't let me pass the array into the function. Is there a workaround to this? How can I pass SensorID[i] into the function()?

1 Answers1

1

As the callback function is executed only after the loop has finished, i will have moved on. To avoid this, use let i instead of var i in the for construct: that will create a separate i variable for each iteration.

trincot
  • 317,000
  • 35
  • 244
  • 286