0

I'm broadcasting a set of coordinates and want that coordinates shown by a marker updated in every second.

         var broadcastData = function (data) {
           console.log("broadcasting data");
           $rootScope.$broadcast('broadcast-started', data);
        };


            var waitingTime = 1000;

            for(var i =0; i<data.length; i++){
                var element = data[i];

                var coordinates = new Object();
                coordinates.latitude = element.LATITUDE;
                coordinates.longitude = element.LONGITUDE;

                setTimeout(function(){ broadcastData(coordinates);}, waitingTime);
                waitingTime = waitingTime+1000;
            }

Reciever

   $scope.$on('broadcast-started', function (event, args) {
        console.log(args);

        console.log("received");
        marker.setLatLng([args.latitude, args.longitude]);

    });

Output: enter image description here

Problem is even though coordinates are different in each iteration only the first set of coordinates are shown each time? I don't understand why that's happening

Asiri Liyana Arachchi
  • 2,663
  • 5
  • 24
  • 43

1 Answers1

1

You need to use clouser function like this,

for(var i = 0; i < 10; i++) {
(function(i){  
     var element = data[i];

            var coordinates = new Object();
            coordinates.latitude = element.LATITUDE;
            coordinates.longitude = element.LONGITUDE;

            setTimeout(function(){ broadcastData(coordinates);}, waitingTime);
            waitingTime = waitingTime+1000;
})(i);}
Priyanka
  • 354
  • 7
  • 14
  • Why is that and what it does? would you please care to elaborate? – Asiri Liyana Arachchi Nov 03 '16 at 10:31
  • This works btw. It would be really good if you can point out what's wrong with my implementation. – Asiri Liyana Arachchi Nov 03 '16 at 10:38
  • 1
    @AsiriLiyanaArachchi There is nothing wrong about your code, but implementing $timeout function within loop will take last i th value after loop is over. Using clouser , outer function will create new scope, and inside i will take value equal to i in the loop and remains forever. Have a look at 'javascript clousers' for better undestaning, as i am week at English and unable to explain in more technical words. – Priyanka Nov 03 '16 at 11:13