Google 地图 - 动画折线 -- 停止/删除动画

Google Maps - Animated Polyline -- Stop / Remove Animation

我正在从 GPX 文件中在 Google 地图 API V3 上绘制多段线。

鼠标悬停在该多段线上时,我有一个动画点,使用函数 animateRoute();

沿着多段线移动

但是目前,我没有办法删除 mouseout 上的动画点,因此,如果您将 mouseover、mouseout、mouseover 等,您最终会看到多个动画点沿着同一条线移动。

代码片段:(也请参阅下面的完整工作 URL)

var gmarkers = [];

function loadGPXFileIntoGoogleMap(map, filename,recordNum, name, hex_code) {
$.ajax({
    type: "GET",
    url: filename,
    dataType: "xml",
    success: function(xml) {
    var points = [];
    var bounds = new google.maps.LatLngBounds ();
    $(xml).find("trkpt").each(function() {
        var lat = $(this).attr("lat");
        var lon = $(this).attr("lon");

    if((lat != 0) && (lon != 0))
    {
        var p = new google.maps.LatLng(lat, lon);
        points.push(p);
        bounds.extend(p);
    }


    });

    var strokeColor =  "#ff0000";

    var poly = new google.maps.Polyline({
        path: points,
        strokeColor: strokeColor,
        strokeOpacity: 1,
        strokeWeight: 4,
        recordNum: recordNum,
    });

    poly.setMap(map);

    google.maps.event.addListener(poly, 'mouseover', function() {
        var start = {
            path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
            fillColor: '#00ff00',
            fillOpacity: 1,
            strokeColor:'#000000',
            strokeWeight: 4,
            scale: 0.5
        }
        var end = {
            path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
            fillColor: '#FF0000',
            fillOpacity: 1,
            strokeColor:'#000000',
            strokeWeight: 4,
            scale: 0.5
        }
        var markerStart = new google.maps.Marker({
            position: poly.getPath().getAt(0),
            icon: start,
            map: map,
            zIndex: 200,
            scale: 1
        });
        gmarkers.push(markerStart);
        var markerEnd = new google.maps.Marker({
            position: poly.getPath().getAt(poly.getPath().getLength() - 1),
            icon: end,
            map: map,
            zIndex: 200,
            scale: 1
        });
        gmarkers.push(markerEnd);
        var icons =  this.setOptions({
        icons: [{
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                strokeOpacity: 1,
                strokeColor: "#000000",
                strokeWeight: 2,
                scale: 4
            },
        }]});
        animateRoute(poly);


    });

    function animateRoute(line) {
    var count = 0;
        window.setInterval(function() {
            count = (count + 1) % 200;
            var icons = poly.get('icons');
            icons[0].offset = (count / 2) + '%';
            poly.set('icons', icons);
        }, 60);
    }




    google.maps.event.addListener(poly, 'mouseout', function() {
        removeMarkers();
    });

    // fit bounds to track
    map.fitBounds(bounds);
    }
});
}

function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
    gmarkers[i].setMap(null);
}

}
$(document).ready(function() {
var mapOptions = {
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    var map = new google.maps.Map(document.getElementById("map"),
            mapOptions);
    loadGPXFileIntoGoogleMap(map, "cmsAdmin/uploads/blue_and_green_not_comfortable_.gpx","724","Example A","FFFF00");
    loadGPXFileIntoGoogleMap(map, "cmsAdmin/uploads/taraweratrailrouterecce.gpx","431","Example B","4F4CBE");
});

完整的工作示例: https://www.wildthings.club/mapStack.php

将鼠标悬停在蓝线上,您会看到动画点。 鼠标离开,然后在几秒钟后再次悬停 - 第二个点将出现,第一个点仍在继续。 重复,你很快就会有一堆紧张不安的点。

理想情况下,我想删除 mouseout 上的所有动画点。

第二种选择是不添加后续的动画点图标,如果该折线上已经有一个(请注意地图上有多个折线)。

第三个失败的选项是让动画点停止并在到达终点(位置标记结束)后移除,这样至少它不会循环。

我试过将图标放入一个数组中,然后从那里删除(就像我对 gmarkers 数组和 removeMarkers() 所做的那样,但没有成功。

我也玩过 Animate google maps polyline 但这只适用于直线点对点,而不是遵循 GPX 文件中的一系列点。

任何帮助,非常感谢 干杯

您应该使用根据该网站上的代码改编的 window.clearInterval() function to remove the interval you are using to animate the icon on the polyline. You should save the id when call window.setInterval() in animateRoute(). Here is a simple JSBin proof of concept。在我的代码中,我只是简单地使用全局 id 变量,并在 animateRoute():

中更新该变量
<!DOCTYPE html>
<html>
  <head>
    <title>Polyline path</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
    html, body, #map {
      height: 100%;
      width: 100%;
    }
</style>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    var map;
    var id;
    var gmarkers = [];
    var gmarkersicons = [];

    function initMap() {

      var mapOptions = {
            zoom: 3,
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            center: {lat: 9.291, lng: -157.821}
        };
      map = new google.maps.Map(document.getElementById("map"),
                mapOptions);

       var points = [
         {lat: 37.772, lng: -122.214},
         {lat: 21.291, lng: -157.821},
         {lat: -18.142, lng: 178.431},
         {lat: -27.467, lng: 153.027}
       ];
     var poly = new google.maps.Polyline({
            path: points,
            strokeColor: "red",
            strokeOpacity: 1,
            strokeWeight: 4,
            recordNum: "test"
        });

        poly.setMap(map);

        google.maps.event.addListener(poly, 'mouseover', function() {
            var start = {
                path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
                fillColor: '#00ff00',
                fillOpacity: 1,
                strokeColor:'#000000',
                strokeWeight: 4,
                scale: 0.5
            }
            var end = {
                path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
                fillColor: '#FF0000',
                fillOpacity: 1,
                strokeColor:'#000000',
                strokeWeight: 4,
                scale: 0.5
            }
            var go = {
                path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
                fillColor: '#000000',
                fillOpacity: 1,
                strokeColor:'#fff',
                strokeWeight: 4,
                scale: 0.5
            }
            var markerStart = new google.maps.Marker({
                position: poly.getPath().getAt(0),
                icon: start,
                map: map,
                zIndex: 200,
                scale: 1
            });
            gmarkers.push(markerStart);
            var markerEnd = new google.maps.Marker({
                position: poly.getPath().getAt(poly.getPath().getLength() - 1),
                icon: end,
                map: map,
                zIndex: 200,
                scale: 1
            });
            gmarkers.push(markerEnd);
            var icons =  this.setOptions({
            icons: [{
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    strokeOpacity: 1,
                    strokeColor: "#000000",
                    strokeWeight: 2,
                    scale: 4
                },
            }]});
            this.setOptions({
                strokeColor: "red",
                scale: 1,
                strokeWeight:15,
                strokeOpacity:.6
                });

            var contentString = "Testing";
            var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });
            infowindow.open(map, markerStart);
            id = animateRoute(poly);
        });

        function animateRoute(line) {
          var count = 0;
          var id = window.setInterval(function() {
            count = (count + 1) % 200;
            var icons = poly.get('icons');
            icons[0].offset = (count / 2) + '%';
            poly.set('icons', icons);
          }, 60);
          return id;
        }

        google.maps.event.addListener(poly, 'mouseout', function() {
            removeMarkers();
            this.setOptions({strokeColor:"red",strokeWeight:4,strokeOpacity:1});
            this.setOptions( { suppressMarkers: true } );
            this.setOptions({
            icons: [{}]});
            window.clearInterval(id);
        });


     function removeMarkers(){
       for(i=0; i<gmarkers.length; i++){
         gmarkers[i].setMap(null);
       }
     }
 }

$(document).ready(function() {
initMap();
});

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