Search code examples
javascriptgoogle-maps-api-3google-fusion-tables

FOR loop to iterate through array


I have an array that I would like to iterate through with a for loop to avoid excessive code. I would like to take the following:

var mySchool = document.getElementById(varID[0]);
google.maps.event.addDomListener(mySchool,'click', function() {
    filterMap(layer, tableId, map);                 
});

and have it be more like:

for(var i=0; i < varID.length; i++){
    var mySchool = document.getElementById(varID[i]);
    google.maps.event.addDomListener(mySchool,'click', function() {
        filterMap(layer, tableId, map);
    }); 
}

I've been doing some reading and i suspect it has something to do with Javascript closures but can't for the life of me get it to work with the various code examples i have found. I'm hoping the experienced eye can spot something i'm missing from this Javascript newbie.

My complete code looks like this:

//There are more items in my array but i wanted to keep it short here   
var varID = [
    "adamRobertson",
    "blewett",
    "brentKennedy"
];

var tableId = '1yc4wo1kBGNJwpDm6e-eJY_KL1YhQWfftjhA38w8';

function initialize() {
    var map = new google.maps.Map(document.getElementById('map-canvas'), {
      center: new google.maps.LatLng(49.491052,-117.304484),
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var layer = new google.maps.FusionTablesLayer();
    filterMap(layer, tableId, map);

    //Trying to get this to work
    for(var i=0; i < varID.length; i++){
        var mySchool = document.getElementById(varID[i]);
            google.maps.event.addDomListener(mySchool,'click', function() {
                filterMap(layer, tableId, map);                 
        });
    }

    //Trying to avoid this 25 times     
    /*
    google.maps.event.addDomListener(document.getElementById(varID[0]),
        'click', function() {
            filterMap(layer, tableId, map);
    });
    */
}

// Filter the map based on checkbox selection.
function filterMap(layer, tableId, map) {
    var where = generateWhere();

    if (where) {
      if (!layer.getMap()) {
        layer.setMap(map);
      }
      layer.setOptions({
        query: {
          select: 'Location',
          from: tableId,
          where: where
        }
      });
    } else {
      layer.setMap(null);
    }
}

// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
    var filter = [];
    var schools = document.getElementsByName('school');
    for (var i = 0, school; school = schools[i]; i++) {
      if (school.checked) {
        var schoolName = school.value.replace(/'/g, '\\\'');
        filter.push("'" + schoolName + "'");
      }
    }
    var where = '';
    if (filter.length) {
      where = "School IN (" + filter.join(',') + ')';
    }
    return where;
}

google.maps.event.addDomListener(window, 'load', initialize);

The HTML basically contains input for checkboxes to turn my polygons on and off.

Thanks in advance for any help.


Solution

  • I think it will help if you change the code to this:

    var mySchool; var limit = varID.length;
    for(var i=0; i < limit; i++){
        mySchool = document.getElementById(varID[i]);
        (function(){
    
            google.maps.event.addDomListener(mySchool,'click', function() {
                filterMap(layer, tableId, map);                 
            });
    
        }());
    }
    

    I took the for limit calculation out of the loop so that will save some speed too.

    I haven't used the maps api so you may have to add some arguments to the closure.

    var mySchool; var limit = varID.length;
    for(var i=0; i < limit; i++){
        mySchool = document.getElementById(varID[i]);
        (function(s, l, t, m){
    
            google.maps.event.addDomListener(s,'click', function() {
                filterMap(l, t, m);                 
            });
    
        }(mySchool, layer, tableId, map));
    }
    

    I'm not sure which args are needed, but you'll probably figure it out.