crockpotveggies crockpotveggies - 1 year ago 207
Javascript Question

Extend Google Maps marker to animate smoothly on update?

Using the Google Maps API v3 I've been able to update multiple positions of markers via an AJAX call. However, it lacks any transition. Code below:

if ( !latlong.equals( point.latlong ) ) {
point.latlong = latlong;

The drawback is that
has no native animation method. Does anyone know any methods for extending
so the marker can fluently "move" from it's old to new position? Or any methods available? I have not been able to find any documentation. Thanks!

Answer Source

I did not find any native way to create this animation. You can create your own animation by stepping the position from the current point to the final point using the setPosition. Here is a code snippet to give you an idea:

var map = undefined;
var marker = undefined;
var position = [43, -89];

function initialize() {

    var latlng = new google.maps.LatLng(position[0], position[1]);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "Your current location!"

    google.maps.event.addListener(map, 'click', function(me) {
        var result = [, me.latLng.lng()];

var numDeltas = 100;
var delay = 10; //milliseconds
var i = 0;
var deltaLat;
var deltaLng;
function transition(result){
    i = 0;
    deltaLat = (result[0] - position[0])/numDeltas;
    deltaLng = (result[1] - position[1])/numDeltas;

function moveMarker(){
    position[0] += deltaLat;
    position[1] += deltaLng;
    var latlng = new google.maps.LatLng(position[0], position[1]);
        setTimeout(moveMarker, delay);

This can probably be cleaned up a bit, but will give you a good start. I am using JavaScript's setTimeout method to create the animation. The initial call to 'transition' gets the animation started. The parameter to 'transition' is a two element array [lat, lng]. The 'transition' function calculates the step sizes for lat and lng based upon a couple of animation parametes (numDeltas, delay). It then calls 'moveMarker'. The function 'moveMarker' keeps a simple counter to indicate when the marker has reached the final destination. If not there, it calls itself again.

Here is a jsFiddle of the code working:

Hope this helps.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download