Udders
Udders

Reputation: 6976

looping in javascript getting unexpected results

I am trying to add markers to a google map, and these markers have a number on them, however what I get is the same marker repeated throughout the loop why is this? Here is my code,

function codeAddress() {
var address = ['hd3 3nn', 'hd6 3qf'];
for (var i = 0; i < address.length; i++) {
    var num = i;
    geocoder.geocode( { 'address': address[i]}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var image = new google.maps.MarkerImage('/~udders/wp-content/themes/muslenh2/img/markers/marker' + num + '.png',
                  new google.maps.Size(20, 34),
                  new google.maps.Point(0, 0),
                  new google.maps.Point(10, 34));
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

}

Basically this /~udders/wp-content/themes/m/img/markers/marker' + num + '.png is creating, /~udders/wp-content/themes/m/img/markers/marker1.png the one is the number from the last loop, and it seems to be overwriting all the previous icon images.

Upvotes: 0

Views: 53

Answers (1)

Stuart
Stuart

Reputation: 9858

This is because of how Javascript closures work.

You could work around it by making a separate function which returns a callback function.

function codeAddress() {
    var address = ['hd3 3nn', 'hd6 3qf'];
    for (var i = 0; i < address.length; i++) {
        geocoder.geocode({'address': address[i]}, getGeocoderCallBack(i));
    }
}

function getGeocoderCallback(num) {
    return function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var image = new google.maps.MarkerImage('/~udders/wp-content/themes/muslenh2/img/markers/marker' + num + '.png',
            new google.maps.Size(20, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(10, 34));
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    };
}

Upvotes: 1

Related Questions