谷歌地图事件

Google Maps Events

本文关键字:事件 谷歌地图      更新时间:2023-09-26

我有一个谷歌地图在我的项目与多个标记。我的目标是当我点击标记时,执行一个函数(toggleBounce)。所以我将每个标记添加到google。maps。event中。addListener,像这样:

for(var i in markers){
  google.maps.event.addListener(marker[i], 'click', toggleBounce);
}

好好工作!所以我的问题是在函数toggleBounce中,我如何传递标记的数量?

function toggleBounce() {
  if (marker[WHAT I NEED TO PUT HERE?].getAnimation() != null) {
    marker[WHAT I NEED TO PUT HERE?].setAnimation(null);
  } 
  else {
    marker[WHAT I NEED TO PUT HERE?].setAnimation(google.maps.Animation.BOUNCE);
  }
}

在事件处理程序事件中使用this(它是标记):

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

概念验证

代码片段:

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(-33.92, 151.25),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: map
    });
    google.maps.event.addListener(marker, 'click', toggleBounce);
  }
}
google.maps.event.addDomListener(window, 'load', initMap);
function toggleBounce() {
  if (this.getAnimation() != null) {
    this.setAnimation(null);
  } else {
    this.setAnimation(google.maps.Animation.BOUNCE);
  }
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

我创建了一个活塞,它可能会帮助你。

http://plnkr.co/edit/4hFdmxji9C74ymBL1qtS?p =

预览
var createMarker = function (info){                   
var marker = new google.maps.Marker({
                    map: scope.map,
                    position: new google.maps.LatLng(info.lat, info.lon),
                    title: info.place
                });
                google.maps.event.addListener(marker, 'click', function(){
                    //do your stuff
                if (marker.getAnimation() != null) {
                marker.setAnimation(null);
                } 
               else {
               marker.setAnimation(google.maps.Animation.BOUNCE);
               }
             });                    
            }
            for (var i = 0; i < items.length; i++){
                items[i].id=i+'AM@_255';
                createMarker(items[i]);
            }