Javascript MindFuck: Google Maps GeoCoder Callback with Parameters

If you have ever tried to geocode with google maps you have perhaps noticed that you can’t easy pass more data to the callback function. And geocoding on an array of addresses won’t work too, because you get always the result for the last entry of your array.

To solve that issues you must encapsulate your callback into another anonymous function (closure) that returns itself to the callback.

 
var locations = [];
locations.push({address:'hauptplatz 1, 4020 linz, austria', 'otherInfo'=>'info'});
 
for(idx in locations) {
    var location = locations[idx];
    var address = location['address'];
    geocoder.geocode({'address':address}, function(location, idx){
        return(function(results, status){
            if (status == google.maps.GeocoderStatus.OK) {
                var latlng = results[0].geometry.location;
 
                console.log(location);
                console.log(idx);
            }
        });
    }(location, idx));
}