Geochart loop listener

by cmoreira

HTML

<script src="http://www.google.com/jsapi?fake=.js"></script>
Alerts on this map don't work as they should.
<div id="map_1"></div>
Only after this map is clicked.
<div id="map_2"></div>

JavaScript

google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawVisualization);

var iwmparam = [{
    "id":"1",
    "txt":"Alert From ID 1"
}, {
    "id":"2",
    "txt":"Alert From ID 2"
}];

var message = new Array();

function drawVisualization() {
    var geocharts = {};
    var dataTables = {};
    for (var key in iwmparam) {
        var id = parseInt(iwmparam[key]['id']);
        
        message[id] = iwmparam[key]['txt'];
        
        dataTables[key] = google.visualization.arrayToDataTable([
            ['Country', 'Popularity'],
            ['Germany', 200],
            ['United States', 300],
            ['Brazil', 400],
            ['Canada', 500],
            ['France', 600],
            ['RU', 700]
        ]);
        
        geocharts[key] = new google.visualization.GeoChart(document.getElementById('map_'+id));
        
        // use a closure to lock the value of "key" in this iteration of the loop to "x" inside the closure
        google.visualization.events.addListener(geocharts[key], 'select', (function(x) {
            return function () {
                var selection = geocharts[x].getSelection();
                
                if (selection.length == 1) {
                    var selectedRow = selection[0].row;
                    var selectedRegion = dataTables[x].getValue(selectedRow, 0);
                    
                    alert(iwmparam[x]['txt'] + " " + selectedRegion);
                }
            }
        })(key));
        
        geocharts[key].draw(dataTables[key], {
            region:'world',
            width: '500', 
            legend: 'none'
        });
    }    
}