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

时间:2018-03-28 17:50:12

标签: google-maps google-maps-api-3 google-maps-markers google-maps-styled

我正在使用GPX文件在Google Maps API V3上绘制折线。

在该折线的鼠标悬停时,我有一个动画点,沿着折线移动,使用函数animateRoute();

目前,我还没有办法删除鼠标输出上的动画点,因此,如果你将鼠标悬停,鼠标移开,鼠标悬停等移动,最终会有多个动画点沿着同一条线移动。

代码段:(请参阅下面的完整工作网址)

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

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

理想情况下,我想删除鼠标输出上的所有动画点。

如果该polyLine上已存在一个动画点图标,则第二个选项是不添加后续动画点图标(注意地图上有多个polyLine)。

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

我已尝试将图标放入数组然后从那里删除(就像我使用gmarkers数组和removeMarkers()一样,但没有运气。

我还玩Animate google maps polyline,但这只是直线点对点,而不是跟随GPX文件中的一系列点。

任何帮助,非常感谢 干杯

1 个答案:

答案 0 :(得分:1)

您应该使用window.clearInterval()功能删除用于为折线上的图标设置动画的间隔。在id中致电window.setInterval()时,您应该保存animateRoute()。这是根据该网站上的代码改编的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>