Animate google maps polyline

emathias picture emathias · May 28, 2013 · Viewed 19.5k times · Source

I'd like to draw an animated (geodesic) polyline in google maps, a bit like this: http://planefinder.net/route/SFO/

I found many tutorials on how to animate a symbol along a polyline, but nothing about animating the polyline itself from the source to the destination.

Any hints ? Where should I start ?

Any help is really appreciated.

Answer

Pedro Cattori picture Pedro Cattori · Jul 29, 2013

I've had some success with the following:

 var departure = new google.maps.LatLng(dept_lat, dept_lng); //Set to whatever lat/lng you need for your departure location
 var arrival = new google.maps.LatLng(arr_lat, arr_lng); //Set to whatever lat/lng you need for your arrival location
 var line = new google.maps.Polyline({
      path: [departure, departure],
      strokeColor: "#FF0000",
      strokeOpacity: 1,
      strokeWeight: 1,
      geodesic: true, //set to false if you want straight line instead of arc
      map: map,
 });
 var step = 0;
 var numSteps = 250; //Change this to set animation resolution
 var timePerStep = 5; //Change this to alter animation speed
 var interval = setInterval(function() {
     step += 1;
     if (step > numSteps) {
         clearInterval(interval);
     } else {
         var are_we_there_yet = google.maps.geometry.spherical.interpolate(departure,arrival,step/numSteps);
         line.setPath([departure, are_we_there_yet]);
     }
 }, timePerStep);

This is basically using an interval to redraw the path. At each step, the visible, animated path makes up a larger percentage of the total path from departure to arrival until finally the arrival location is reached.