tristanojbacon
tristanojbacon

Reputation: 456

Google Maps API - bouncing marker issue

When a marker is selected, I want it to bounce. When I click on another marker, I want the first one to stop bouncing, and the other to then start bouncing. I assumed that this was achievable by simple doing this

function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
 document.getElementById('loc-info').innerHTML = html;
 if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
});
}

Instead, the first marker will continue to bounce until it is clicked again, which I don't want to happen. Any thoughts?

Upvotes: 2

Views: 2547

Answers (1)

doublesharp
doublesharp

Reputation: 27667

You need to keep track of the "current" marker and set its animation to null before bouncing the new marker and setting it to the "current" marker.

// track marker that is currently bouncing
var currentMarker = null;

function bindInfoWindow(marker, map, infoWindow, html) {
    google.maps.event.addListener(marker, 'click', function() {
        document.getElementById('loc-info').innerHTML = html;
        // remove the bounce from the "old" marker
        if (currentMarker) currentMarker.setAnimation(null);
        // set this marker to the currentMarker
        currentMarker = marker;
        // add a bounce to this marker
        marker.setAnimation(google.maps.Animation.BOUNCE);

    });
}

Your previous code is only looking at the marker that was just clicked - if it isn't clicking (the start state) then you make it bounce. The next click checks to see if it is bouncing (it is), and stops it. You could add the same logic to the code above if you want a second click to stop the bouncing.

Upvotes: 5

Related Questions