jsfiddle:http://jsfiddle.net/4mtyu/373/
我试图在一个小模块中包装地图api我可以传递一个对象数组,用于在地图上绘制标记。
下面的代码有效,但动画(toggleBounce())仅附加到地图上绘制的其中一个标记。当我点击任何标记时,相同的标记会反弹。关于点击监听器如何连接一定是个问题,但我不知道自己做错了什么。
我的模块:
var gmapsModule = (function () {
//private
function toggleBounce(marker) {
console.dir(marker);
//make markers bounce when selected
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
function drawMarkers( mapOptions, branchMarkers, animation ) {
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (var prop in branchMarkers) {
if( branchMarkers.hasOwnProperty( prop ) ) {
var branch = branchMarkers[prop];
var markerCoordinates = new google.maps.LatLng(branch.lat,branch.lng);
marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
//icon: markerImageOptions,
position: markerCoordinates,
title: branch.branchname
});
//draw marker on map
marker.setMap(map);
google.maps.event.addListener(marker, 'click', animation(marker));
} //end if
} // end for
}
//public
return {
drawMarkers: drawMarkers,
toggleBounce: toggleBounce
};
})();
使用模块生成地图
var branchObjs = [
{
branchname: 'sssssssssss',
branchnum: '1',
lat: '20.804167',
lng: '-53.169444'
},
{
branchname: 'oooooooooo',
branchnum: '2',
lat: '20.824167',
lng: '-53.189444'
}
];
var mapOptions = {
center: new google.maps.LatLng(20.804167,-53.169444),
zoom: 9
};
google.maps.event.addDomListener(window, 'load',
gmapsModule.drawMarkers(mapOptions,branchObjs,gmapsModule.toggleBounce));
答案 0 :(得分:1)
您需要保留对所有标记的引用并切换每个标记的动画状态。目前,您只保留对最后一个的引用,因此这是您唯一可以更改的内容。
var gmapsModule = (function () {
//private
markers = [];
function toggleBounce() {
//make the clicked marker bounce
if (this.getAnimation() != null) {
this.setAnimation(null);
} else {
this.setAnimation(google.maps.Animation.BOUNCE);
}
}
}
// --------------------------------------------- -------
if (branchMarkers.hasOwnProperty(prop)) {
var branch = branchMarkers[prop];
var markerCoordinates = new google.maps.LatLng(branch.lat, branch.lng);
var marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
//icon: markerImageOptions,
position: markerCoordinates,
title: branch.branchname
});
gmapsModule.markers.push(marker); // keep reference to marker
// --------------------------------------------- -------