简体   繁体   English

动画不同的标记API V3谷歌地图

[英]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. 提前致谢。

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 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM