动画谷歌地图弹跳标记



我试图在我的标记上实现反弹动画,我遵循了这个文档,它只在我的数组中动画第一个标记。我试着把我的标记上的位置调用到事件监听器中,但这似乎不起作用。有什么建议吗?

下面是我的代码:
for(var i = 0; i < locationArray().length; i++){
   var locations = locationArray()[i].location;
   var title = locationArray()[i].title;
   var marker = new google.maps.Marker({
       position: locations,
       map: map,
       title: title,
       icon: defaultMarker,
       animation: google.maps.Animation.DROP
           });
  google.maps.event.addListener(marker,'click', function(){
       if (marker.getAnimation() !== null) {
            marker.setAnimation(null);
         } else {
           marker.setAnimation(google.maps.Animation.BOUNCE);
             }
            console.log(marker);
});

这是一个常见的错误。你可能认为循环将点击事件绑定到每个标记,但实际上并非如此。由于click事件发生在创建标记之后,因此它只适用于最后一个标记。您必须将必要的参数传递给函数并在那里创建标记。

这里的locationarray不是一个函数,只是一个数组。

工作小提琴:https://jsfiddle.net/ergec/8kdx7az6/

 var map;
    google.maps.event.addDomListener(window, "load", function() {
        var map = new google.maps.Map(document.getElementById("map_div"), {
            center: new google.maps.LatLng(33.808678, -117.918921),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        function createMarker(locationArray) {
            var locations = locationArray.location;
            var title = locationArray.title;
            var marker = new google.maps.Marker({
                position: locations,
                map: map,
                title: title,
                animation: google.maps.Animation.DROP
            });
    
            google.maps.event.addListener(marker, 'click', function() {
                if (marker.getAnimation() !== null) {
                    marker.setAnimation(null);
                } else {
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                }
            });
        }
        locationArray = [
            {location: new google.maps.LatLng(33.808678, -117.918921), title: "1"},
            {location: new google.maps.LatLng(33.818038, -117.928492), title: "2"},
            {location: new google.maps.LatLng(33.803333, -117.915278), title: "3"}
        ];
        for (var i = 0; i < locationArray.length; i++) {
            createMarker(locationArray[i]);
        }
    });
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&v=3"></script>
   
    <div id="map_div" style="height: 400px;"></div>

最新更新