panTo() method interfering with bounce animation in Google Maps Javascript API

Viewed 164

I'm implementing a relatively simple Google Map that has various markers in it. I'm adding a listener to the marker such that it bounces up and down when clicked, and the map pans to it.

The expected behavior is that you click one pin and it bounces, you click it again and it stops. Also, if you click a pin and then click another one, the first stops bouncing and the second starts. Pretty intuitive.

What's happening, however, is that it stops working after two or three 'back and forths' between pins. I've narrowed down the culprit to the behavior of the map panning to the pin (panTo()). If I remove that, it works well.

The attached code reproduces the issue. If you comment the line with the panTo() method, you can see how it works fine.

Any thoughts on why this happens and how to fix it?

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <style type="text/css">
      #map {
        height: 100%;
      }
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script>
    let map;
    markers = [];

    positions = [
        {lat : 50.46818409999999, lng: 30.5252753},
        {lat : 50.46220959999999, lng: 30.5153674},
    ];

    function initMap() {
        map = new google.maps.Map(document.getElementById("map"), {
          center: { lat: 50.462, lng: 30.514 },
          zoom: 12,
        });
        dropmarkers();
    };

    function dropmarkers() {
        
        for (let i = 0; i < positions.length; i++) {

            window.setTimeout(() => {

                var marker = new google.maps.Marker({
                    position: {lat: positions[i]['lat'], lng: positions[i]['lng']},
                    animation: google.maps.Animation.DROP
                });

                markers.push(marker);

                marker.addListener("click", function () {
                    toggleAnimation(marker);
                    map.panTo({lat: positions[i]['lat'], lng: positions[i]['lng']});
                    map.setZoom(14);
                });

                marker.setMap(map);

            }, i * 200);
        };
    };

    function toggleAnimation(marker) {
        if (marker.getAnimation() !== null) {
            marker.setAnimation(null);
        } else {
            for (var j = 0; j < markers.length; j++) {
                markers[j].setAnimation(null);
            }
            marker.setAnimation(google.maps.Animation.BOUNCE);
        };
    };

    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

0 Answers
Related