I have a map integrated on my web page with marker animation. I have multiple markers in the map. I want to achieve something like, when any of the marker is clicked then other marker's animation should stop which is currently running.
Currently i am able to stop animation of the same marker on the marker click. There must be some marker object i should get in the case of multiple markers.
So far i have done this.
latlngarray is an array with lattitude and longitude in object format.
var centerlatlng={center lat lng are here};
var zoomlevel=zoomlevel is here;
function initMap(){
map = new google.maps.Map(document.getElementById('map'),{
center: centerlatlng,
zoom: zoomlevel
});
if(latlngarray.length > 0){
for(i=0; i < latlngarray.length; i++){
marker = new google.maps.Marker({
position: latlngarray[i],
map: map
});
marker.addListener('click', function(){
toggleBounce(this);
map.setZoom(10);
map.setCenter(marker.getPosition());
});
}
}}
function toggleBounce(ele){
if(ele.getAnimation() !== null){
ele.setAnimation(null);
}else{
ele.setAnimation(google.maps.Animation.BOUNCE);
}}
答案 0 :(得分:5)
创建一个包含所有标记引用的数组,遍历该数组,取消所有标记上的动画,然后在点击的标记上设置动画。
marker.addListener('click', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setAnimation(null);
}
toggleBounce(this);
map.setZoom(10);
map.setCenter(marker.getPosition());
});
代码段
var map;
var centerlatlng = {
lat: 37.4419,
lng: -122.1419
};
var zoomlevel = 13;
var latlngarray = [{lat: 37.4418834, lng: -122.1430195}, // Palo Alto, CA, USA
{lat: 37.4688273, lng: -122.1410751}, //East Palo Alto, CA, USA
{lat: 37.424106, lng: -122.1660756}, // Stanford, CA, USA
{lat: 37.4529598, lng: -122.1817252} // Menlo Park, CA, USA
];
function initMap() {
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: centerlatlng,
zoom: zoomlevel
});
if (latlngarray.length > 0) {
for (i = 0; i < latlngarray.length; i++) {
var marker = new google.maps.Marker({
position: latlngarray[i],
map: map
});
markers.push(marker);
marker.addListener('click', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setAnimation(null);
}
toggleBounce(this);
map.setZoom(10);
map.setCenter(marker.getPosition());
});
}
}
}
function toggleBounce(ele) {
if (ele.getAnimation() !== null) {
ele.setAnimation(null);
} else {
ele.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addDomListener(window, "load", initMap);
&#13;
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;