我试图在我的标记上实现反弹动画,我按照文档进行了操作,并且只对我的数组中的第一个标记进行了动画处理。我试着将我的标记上的位置调用到事件监听器中,但这似乎无法正常工作。有什么建议吗?
这是我的代码:
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);
});
答案 0 :(得分:0)
这是一个常见的错误。您可能认为该循环将点击事件绑定到每个标记但实际上并非如此。由于点击事件在创建标记后发生,因此它仅适用于最后一个。您必须将必要的参数传递给函数并在那里创建标记。
此处的BTW位置阵列不仅仅是一个数组函数。
工作小提琴: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]);
}
});
&#13;
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&v=3"></script>
<div id="map_div" style="height: 400px;"></div>
&#13;