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

2
  • Is the object the last object in data? I'm guessing you're changing the reference coordinates Commented Nov 3, 2016 at 10:31
  • what did you mean by that ? didn't get it Commented Nov 3, 2016 at 10:34

1 Answer 1

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);}
Sign up to request clarification or add additional context in comments.

3 Comments

Why is that and what it does? would you please care to elaborate?
This works btw. It would be really good if you can point out what's wrong with my implementation.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.