简体   繁体   中英

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
            );
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM