Animate marker with specific speed

Animate a marker on Google maps with a specific speed (km/h).

by Wolf

HTML

<script src="http://maps.google.com/maps/api/js?sensor=true&amp;libraries=geometry"></script>
<div id="map_canvas"></div>

CSS

#map_canvas {
  width: 600px;
  height: 450px;
}

JavaScript

var map, marker, circle;
var fps = 30;
var duration = 10;
var current_coords = {latitude: 51.5, longitude: -0.25, accuracy: 500};
var new_coords = {latitude: 51.5, longitude: 0.25, accuracy: 100};
var latitude_offset = (new_coords.latitude - current_coords.latitude) / (fps * duration);
var longitude_offset = (new_coords.longitude - current_coords.longitude) / (fps * duration);
var accuracy_offset = (new_coords.accuracy - current_coords.accuracy) / (fps * duration);

function moveMarker (i) {
  if (i <= (fps * duration)) {
    setTimeout(function () {
      circle.setRadius(current_coords.accuracy + accuracy_offset * i);
      var lat_lng = new google.maps.LatLng(current_coords.latitude + latitude_offset * i, current_coords.longitude + longitude_offset * i);
      map.setCenter(lat_lng);
      moveMarker(i + 1);
    }, (1 / fps) * 1000);
  }
  else
    current_coords = new_coords;
}

function initialize () {
  var lat_lng = new google.maps.LatLng(current_coords.latitude, current_coords.longitude);

  var myOptions = {
    zoom: 14,
    center: lat_lng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  marker = new google.maps.Marker({
    map: map
  });
  
  circle = new google.maps.Circle({
    map: map,
    radius: current_coords.accuracy,
    strokeWeight: 0,
    fillColor: '#AA0000',
    fillOpacity: 0.2
  });

  map.addListener('center_changed', function(e) {
      marker.setPosition(map.getCenter());
  });


//  circle.bindTo('center', marker, 'position');
  marker.setPosition(lat_lng);
  marker.setMap(map);
  circle.setMap(map);
  map.setCenter(lat_lng);
  
  google.maps.event.addListenerOnce(map, 'idle', function () {
    moveMarker(1);
  });
}

initialize();