'google maps animated marker moving

So im trying to move marker smoothly, but id doesnt work. Marker is moving, but not smoothly, the same result i can have if i will write

marker[n].setPosition(moveto); 

i have displayed all variables in console, and its fine, all increases by right way, but it seems like

marker[n].setPosition(latlng);

is called only at the last iteration of cycle.

here is my code:

function animatedMove(n, current, moveto){
        var lat = current.lat();
        var lng = current.lng();

        var deltalat = (moveto.lat() - current.lat())/100;
        var deltalng = (moveto.lng() - current.lng())/100;

        for(var i=0;i<100;i++){
            lat += deltalat;
            lng += deltalng;

            latlng = new google.maps.LatLng(lat, lng);

            setTimeout(
                function(){
                    marker[n].setPosition(latlng);
                },10
            );
        }
    }


Solution 1:[1]

What your code is doing is

for(var i=0;i<100;i++){
// compute new position
// run function "f" that updates position of marker after a delay of 10

What happens is that by the time the function "f" (((function(){marker[n].setPosition(latlng);}) runs after the delay, the cycle has already finished and it has reached the final position for the marker.

Following https://stackoverflow.com/a/24293516/2314737 here's one possible solution

function animatedMove(n, current, moveto) {
  var lat = current.lat();
  var lng = current.lng();

  var deltalat = (moveto.lat() - current.lat()) / 100;
  var deltalng = (moveto.lng() - current.lng()) / 100;

  for (var i = 0; i < 100; i++) {
    (function(ind) {
      setTimeout(
        function() {
          var lat = marker.position.lat();
          var lng = marker.position.lng();

          lat += deltalat;
          lng += deltalng;
          latlng = new google.maps.LatLng(lat, lng);
          marker.setPosition(latlng);
        }, 10 * ind
      );
    })(i)
  }
}

you can look at a demo here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2314737