0

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.

4

1 回答 1

2

您需要保留对要设置动画的所有标记的引用,然后将动画设置在正确的标记上。您发布的代码只有一个标记。

解决问题的一种方法是使用函数闭包:

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);
        }
      });
}

工作示例

于 2013-08-26T04:47:30.533 回答