Chapo58
Chapo58

Reputation: 27

Animating different markers API V3 Google Maps

I have got some markers in my map and i wanted to animate one or another marker depending in which one i made "click". But the animation just work with the last marker that i create and not with the others ones. I tried make the marker as an array but is the same problem. Here is the Code:

<script type="text/javascript">


    var marker = null;
    var address = null;
    var altura = null;

function codeAddress() {
  altura = document.getElementById('altura').value;
  address = document.getElementById('address').value + ' ' + altura ;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
    // Marker
      marker = new google.maps.Marker({
          map: map,
          icon: document.getElementById('icono').value,
          position: results[0].geometry.location,
          animation: google.maps.Animation.DROP
      });
    // Animating Listener
      google.maps.event.addListener(marker, 'click', toggleBounce);
    } else {
      alert('Error: ' + status);
    }
  });
}

function toggleBounce() {
  if (marker.getAnimation() != null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

</script>

Thanks in advance.

Upvotes: 0

Views: 1488

Answers (1)

geocodezip
geocodezip

Reputation: 161384

You need to keep references to all the markers that you want to animate, then set the animation on the correct one. The code you posted only has one marker.

One way of solving your problem is with function closure:

function createMarker(latlng, address, icon){
    // Marker
      var marker = new google.maps.Marker({
          map: map,
          icon: icon,
          position: latlng,
          animation: google.maps.Animation.DROP
      });
    // Animating Listener
      google.maps.event.addListener(marker, 'click', function() {
        if (marker.getAnimation() != null) {
          marker.setAnimation(null);
        } else {
          marker.setAnimation(google.maps.Animation.BOUNCE);
        }
      });
}

working example

Upvotes: 2

Related Questions