Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps Bounce Animation on Marker for a limited period

I wish that a marker bounces for a few seconds and eventually stops automatically.. I am trying this code :

1. globalMarkers[i].setAnimation(google.maps.Animation.BOUNCE);
2. setTimeout(function() {
3.    globalMarkers[i].setAnimation(null)
4. }, 3000);

but for some reason, line 1 executes (hence marker will start bouncing) but the 3rd line returns the following error:

Uncaught TypeError: Cannot call method 'setAnimation' of undefined
        (anonymous function)

Any ideas what it could be?

like image 601
cgval Avatar asked Dec 12 '22 18:12

cgval


1 Answers

This works fine (with a single global marker object)

    marker.setAnimation(google.maps.Animation.BOUNCE);

    setTimeout(function() {
        marker.setAnimation(null)
    }, 3000);

My guess is that you're interating, and your setTimeout i is not in scope. Try this instead:

    for (var x = 0; x < 5; x++) {
        var marker = markers[x];
        marker.setAnimation(google.maps.Animation.BOUNCE);
        stopAnimation(marker);
    }


function stopAnimation(marker) {
    setTimeout(function () {
        marker.setAnimation(null);
    }, 3000);
}

There are some more creative solutions here:

Javascript how to use setTimeout on an iterative list operation?

like image 164
ScottE Avatar answered Mar 08 '23 23:03

ScottE