javascript - 动画不同标记 API V3 Google map

标签 javascript google-maps google-maps-api-3

我的 map 中有一些标记,我想为一个或另一个标记设置动画,具体取决于我“单击”的标记。但动画只适用于我创建的最后一个标记,而不适用于其他标记。 我尝试将标记制作为数组,但遇到了同样的问题。 这是代码:

<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>

提前致谢。

最佳答案

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

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

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

关于javascript - 动画不同标记 API V3 Google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18436599/

相关文章:

python - Google Geocode api 不返回某些 'direct hit' 地址的 postal_code

ios - 在 iPhone 中使用 Google map 进行地理围栏

javascript - 如何在浏览器的新选项卡上显示Base64图像?

javascript - 为什么此 JavaScript 中的 JSON 结果为 "undefined"

ios - 如何设置 GMSURLTileLayer 动画

google-maps - 在 Google map 中绘制方框/矩形选区

javascript - 页面加载时如何将 map 标记设置在 div 中心

javascript - 输入更改时如何通知我?

javascript - Meteor:Facebook 基本 API 调用错误:访问 token

javascript - Google map 未显示在我的网站上