Animate google maps polyline

20,197

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.

Share:
20,197
emathias
Author by

emathias

Updated on February 26, 2020

Comments

  • emathias
    emathias over 4 years

    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.

  • Jabran Saeed
    Jabran Saeed over 10 years
    What if we had several polylines to animate at different speeds. Would setInterval cause trouble? Can this be done using setTimeout?
  • jdog
    jdog over 8 years
    You are passing in are_we_there_yet to setPath which according to the documentation only takes an array. What is the are_we_there_yet and array?