Bounce a pin in google maps once

后端 未结 9 1278
渐次进展
渐次进展 2020-12-13 00:34

I want to bounce a pin on a google map once. The following code will make the marker bounce but it just keeps going...

myPin.setAnimation(google.maps.Animati         


        
9条回答
  •  没有蜡笔的小新
    2020-12-13 01:17

    I have found that in order for a pin to stop animating after a bounce is completed, you need to make the pin draggable. The best way I have found to do this is by using two timeouts:

    1. to remove the animation before the first bounce is complete.
    2. to make the marker not draggable after the first bounce is complete.

    Animations will stop once you make a marker not draggable. I have created a plunker to show what I mean: http://plnkr.co/edit/Gcns3DMklly6UoEJ63FP?p=preview

    The HTML

        

    Bounce marker times.

    The JavaScript

    var marker = null,
        toBounce = null,
        toDrag = null;
    
    function initialize() {
        var mapOptions = {
            zoom: 4,
            center: new google.maps.LatLng(-25.363882, 131.044922)
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(-25.363882, 131.044922),
            map: map
        });
    }
    
    function bounceMarker() {
        var select = document.getElementById("bounceNumber"),
            bounces = parseInt(select.options[select.selectedIndex].value),
            animationTO = (bounces - 1) * 700 + 350,
            dragTO = animationTO + 1000;
    
        // Bounce the marker once
        if (marker.getAnimation() !== null) {
            marker.setAnimation(null);
            clearTimeout(toBounce);
            clearTimeout(toDrag);
            setTimeout(function () {
                marker.setDraggable(false);
            }, 750);
        } else {
            // Workaround to make marker bounce once.
            // The api will finish the current bounce if a marker is set to draggable.
            // So use two timeouts:
            // 1. to remove the animation before the first bounce is complete.
            // 2. to make the marker not draggable after the first bounce is complete.
            // Animations will stop once you make a marker not draggable.
            marker.setDraggable(true);
            marker.setAnimation(google.maps.Animation.BOUNCE);
            toBounce = setTimeout(function () {
                marker.setAnimation(null);
            }, animationTO);
            toDrag = setTimeout(function () {
                marker.setDraggable(false);
            }, dragTO);
        }
    }
    
    
    google.maps.event.addDomListener(window, 'load', initialize);
    

    For as far as I am aware this works cross browser. I have tested in chrome, firefox, safari & opera. I haven't tested this in internet explorer yet.

提交回复
热议问题