Search code examples
leafletpolyline

Redraw Polyline Leaflet


I have a polyline with several points, and I want to redraw it many times inside a loop where I am rearranging the points. I have used setLatLngs function, but it seems to redraw the whole polyline once.

How can I redraw a polyline in a loop?

Here is the code:

test()
{
    for (var i=0;i<100;i++)
    {
        this._polyline.setLatLngs(this.shuffle(this._polylinePoints));
    }
}

Here is a jsfiddle.

Thanks!


Solution

  • So, since if you want to see each iteration's configuration for a certain amount of time..you will probably have to use setTimeout, like in the below example.Or make something recursive instead.Here I just constantly make the timeout larger, a recursive approach is a lot more efficient.

    self = this; 
    for (var i=0;i<100;i++) { 
       setTimeout(function() {
           self._polyline.setLatLngs(self.shuffle(self._polylinePoin‌​ts));
       },1000*i) 
    }
    

    Here is recursive example below

    self = this;
    var runs = 0;
    
    shufflePoints = function() {
        if (runs < 100) {
          runs++;
          self._polyline.setLatLngs(self.shuffle(self._polylinePoin‌​ts));
          setTimeout(function() {
           shufflePoints()
          },1000)
        }
    }