0

I have a map which updates its markers every two seconds. I show toast messages using a 3rd party library that 'something' is wrong at a particular marker. I want the map to be centered and zoomed in to the particular marker when the toast is clicked.

It all works fine for a single marker, but when I have multiple toasts, they all end up showing the last marker (where 'something' did go wrong). I understand this is a problem related to js closures and scopes, but I can't figure out a way to solve it.

if(/*something is wrong at marker*/) {
    if(toastShown.indexOf(i) == (-1))   // check if toast has been shown
    {
        toastShown.push(i);     // mark toast for current marker as shown
        var err = "Problem detected! Click to go to location";
        toastr.error(err, 'Error!', {timeOut: 10000});
        problemAtPoint.push(point);
        index++;
    }       
}

for( var j = 0; j < index; j++) {
    toastr.options.onclick = (function() {
        return function() {
            //alert('clicked!');
            map.setCenter(problemAtPoint[index]);
            map.setZoom(15);  
        }
    })(problemAtPoint[index]);
}
ianace
  • 1,646
  • 2
  • 17
  • 31
Zaxter
  • 2,939
  • 3
  • 31
  • 48
  • in your loop you add an onclick event without using your 'j' iterator.. so if toastr.options is your array of elements it should be toastr.options[j] – webkit Jun 22 '14 at 07:34

1 Answers1

0

You must consider what Javascript Closures are, look this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

This jsfiddle shows an example using a loop

function setupHelp() {
    var helpText = [
        {'id': 'email', 'help': 'Your e-mail address'},
        {'id': 'name', 'help': 'Your full name'},
        {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

    for (var i = 0; i < helpText.length; i++) {
        var item = helpText[i];
        document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
    }
}

Your problem seems to be you're not using the closure parameter

toastr.options.onclick = 
    (function(ITEM) {
       return function() {
           //alert('clicked!');
           map.setCenter(ITEM);
           map.setZoom(15);  
       }
})(problemAtPoint[index]);
Melvinr
  • 514
  • 2
  • 8